Easiest way to open a download window without navigating away from the page
I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.
7 years have passed and I don't know whether it works for IE6 or not, but this prompts 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);
I know the question was asked 7 years and 9 months ago
but many posted solutions doesn't seem to work, for example using an <iframe>
works only with FireFox
and doesn't work with Chrome
.
Best solution:
The best working solution to open a file download pop-up in JavaScript
is to use a HTML
link element, with no need to append the link element to the document.body
as stated 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 am using it this way:
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");
Note:
- You have to use the
link.download
attribute so the browser doesn't open the file in a new tab and fires the download pop-up. - This was tested with several file types (docx, xlsx, png, pdf, ...).
This javascript is nice that it doesn't open a new window or tab.
window.location.assign(url);