The easiest way to open the download window without going from the page

What is the best way for the cross browser to open the download dialog (suppose we can set the content placement: attachment in the headers) without going from the current page or pop-ups that do not work in IE6.

+90
javascript
Jun 30 '09 at 10:40
source share
12 answers

7 years have passed, good. I don't know if this works for IE6, but it calls OpenFileDialog in FF and Chrome.

var file_path = 'host/path/file.ext'; var a = document.createElement('A'); a.href = file_path; a.download = file_path.substr(file_path.lastIndexOf('/') + 1); document.body.appendChild(a); a.click(); document.body.removeChild(a); 
+70
Mar 09 '17 at 13:37
source share

This javascript is good that it does not open a new window or tab.

 window.location.assign(url); 
+176
Aug 26 '11 at 16:52
source share

I always add the target = "_ blank" link to the download link. This will open a new window, but as soon as the user clicks on save, the new window will be closed.

+20
Jul 01 '09 at 12:03
source share

Put this in the section of the HTML header, specifying in the url URL of the file you want to download:

 <script type="text/javascript"> function startDownload() { var url='http://server/folder/file.ext'; window.open(url, 'Download'); } </script> 

Then put this in a body that will start loading automatically after 5 seconds:

 <script type="text/javascript"> setTimeout('startDownload()', 5000); //starts download after 5 seconds </script> 

( From here .)

+14
Jun 30 '09 at 22:44
source share

I was looking for a good way to use javascript to start a file download, like this question. However, these answers did not help. Then I did some xbrowser testing and found that iframe works best in all modern IE> 8 browsers.

 downloadUrl = "http://example.com/download/file.zip"; var downloadFrame = document.createElement("iframe"); downloadFrame.setAttribute('src',downloadUrl); downloadFrame.setAttribute('class',"screenReaderText"); document.body.appendChild(downloadFrame); 

class="screenReaderText" is my class for stylish content that is present but not viewable.

CSS

 .screenReaderText { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } 

same as .visiddenHidden in html5boilerplate

I prefer this for the javascript window.open method, because if the link is broken, the iframe method just does nothing and does not redirect to a blank page, saying that the file cannot be opened.

 window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0'); window.focus(); 
+13
Aug 01 '12 at 21:05
source share

I know that the question was asked 7 years and 9 months ago but many published solutions do not seem to work, for example, using <iframe> only works with FireFox and does not work with Chrome .

The best decision:

The best working solution for opening a popup window for loading a file in JavaScript is to use an HTML link element, without the need to add a link element in document.body as indicated in other answers.

You can use the following function:

 function downloadFile(filePath){ var link=document.createElement('a'); link.href = filePath; link.download = filePath.substr(filePath.lastIndexOf('/') + 1); link.click(); } 

In my application, I use it as follows:

 downloadFile('report/xls/myCustomReport.xlsx'); 

Working Demo:

 function downloadFile(filePath) { var link = document.createElement('a'); link.href = filePath; link.download = filePath.substr(filePath.lastIndexOf('/') + 1); link.click(); } downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf"); 

Remarks:

  • You must use the link.download attribute link.download that the browser does not open the file in a new tab and launches the download popup window.
  • This has been tested with several file types (docx, xlsx, png, pdf, ...).
+7
Apr 20 '17 at 15:05
source share

If the link is to a valid file url, just assign window.location.href.

However, sometimes the link is invalid and an iFrame is required.

Make your usual event.preventDefault to prevent the window from opening, and if you use jQuery this will work:

 $('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() { $(this).remove(); }); 
+5
Aug 05 '13 at 18:19
source share

Changing the location of the window can cause some problems, especially when you have a permanent connection, such as a websocket. Therefore, I always resort to a good old iframe solution.

HTML

 <input type="button" onclick="downloadButtonClicked()" value="Download"/> ... ... ... <iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe> 

Javascript

 function downloadButtonClicked() { // Simulate a link click var url = 'your_download_url_here'; var elem = document.createElement('a'); elem.href = url; elem.target = 'hiddenIframe'; elem.click(); } 
+1
Nov 02 '16 at 3:49 on
source share

Using the HTML5 Blob Object URL API:

 /** * Save a text as file using HTML <a> temporary element and Blob * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file * @param fileName String * @param fileContents String JSON String * @author Loreto Parisi */ var saveBlobAsFile = function(fileName,fileContents) { if(typeof(Blob)!='undefined') { // using Blob var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' }); var downloadLink = document.createElement("a"); downloadLink.download = fileName; if (window.webkitURL != null) { downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = document.body.removeChild(event.target); downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); } else { var pp = document.createElement('a'); pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents)); pp.setAttribute('download', fileName); pp.onclick = document.body.removeChild(event.target); pp.click(); } }//saveBlobAsFile 

 /** * Save a text as file using HTML <a> temporary element and Blob * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file * @param fileName String * @param fileContents String JSON String * @author Loreto Parisi */ var saveBlobAsFile = function(fileName, fileContents) { if (typeof(Blob) != 'undefined') { // using Blob var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' }); var downloadLink = document.createElement("a"); downloadLink.download = fileName; if (window.webkitURL != null) { downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = document.body.removeChild(event.target); downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); } else { var pp = document.createElement('a'); pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents)); pp.setAttribute('download', fileName); pp.onclick = document.body.removeChild(event.target); pp.click(); } } //saveBlobAsFile var jsonObject = { "name": "John", "age": 31, "city": "New York" }; var fileContents = JSON.stringify(jsonObject, null, 2); var fileName = "data.json"; saveBlobAsFile(fileName, fileContents) 
+1
Apr 24 '18 at 8:35
source share

What about:

 <meta http-equiv="refresh" content="5;url=http://site.com/file.ext"> 

This method works in all browsers (I think) and allows you to put a message like: "If the download does not start after five seconds, click here."

If you need it to be with javascript .. well ...

 document.write('<meta http-equiv="refresh" content="5;url=http://site.com/file.ext">'); 

Hello

0
Jun 30 '09 at 23:17
source share

A small / hidden iframe may work for this purpose.

This way you don't have to worry about closing the popup.

0
Jul 01 '09 at 12:13
source share

After several hours of trying, this function was born :) I had a script when I had to display the bootloader while preparing the file for download:

Work in Chrome, Safari and Firefox

 function ajaxDownload(url, filename = 'file', method = 'get', data = {}, callbackSuccess = () => {}, callbackFail = () => {}) { $.ajax({ url: url, method: 'GET', xhrFields: { responseType: 'blob' }, success: function (data) { // create link element let a = document.createElement('a'), url = window.URL.createObjectURL(data); // initialize a.href = url; a.download = filename; // append element to the body, // a must, due to Firefox document.body.appendChild(a); // trigger download a.click(); // delay a bit deletion of the element setTimeout(function(){ window.URL.revokeObjectURL(url); document.body.removeChild(a); }, 100); // invoke callback if any callbackSuccess(data); }, error: function (err) { // invoke fail callback if any callbackFail(err) } }); 
0
Dec 13 '18 at 22:52
source share



All Articles