How to download file without backend [duplicate]

4

I want to force a file to be downloaded and I'm trying both ways.

downloading on the same page:

  var docLocation = window.location.href + 'docs/apresentacao.pdf';
  var iframe = $('<iframe src="' + docLocation + '" class="hidden"></iframe>');

  $('body').append(iframe);

* this way the browser tries to interpret the file and returns the message:

  

Resource interpreted as Document but transferred with MIME type application / pdf

I saw somewhere saying to convert the MIME type to application/octet-stream with a back-end language and this would force the download.

downloading in a new window:

  window.open(docLocation, '_blank');
The problem with this method is that it opens the file in a new (pop-up) window, and because browsers block pop-ups by default, the user would have to allow loading of that window which would eventually cause some users did not see.

    
asked by anonymous 24.01.2017 / 17:32

3 answers

1

If you want to leave it separate in a function:

function download(uri, nome) {
  var link = document.createElement("a");
  link.download = nome;
  link.href = uri;
  link.click();
}
    
24.01.2017 / 17:53
4

You can do this, if you see correctly, using the download attribute:

<a href="http://www.w3schools.com/css/trolltunga.jpg" download>download</a>

In your case it would be:

<a href="http://CAMINHO/PARA/docs/apresentacao.pdf" download>download pdf</a>

To detect if this attribute is compatible with the browser you can use modernizr and create a a element to verify:

if("download" in document.createElement("a")) {
    alert('É compatível');
}

Font
Compatibilities
Other Form

    
24.01.2017 / 17:33
0

You can use the following HTML5 TAG:

<a href="your_link" download> file_name </a>

However, it does not work in all browsers. Follow the W3Schools documentation to identify compatible browsers.

    
24.01.2017 / 17:38