I use javascript to generate a file and download it.
It seems, that depending on the version of chrome, the download file names can be auto renamed to 'download'. Is there a way to avoid it?
this is my code:
var link = document.createElement("a");
link.setAttribute("href", 'data:application/octet-stream,' + 'file content here');
link.setAttribute("download", 'file1.txt');
link.click();
This is not a duplicated question, because I'm using the latest Chrome and the previously suggested hyperlink is exactly what I'm using. I think, Chrome v34 works fine, but once my Chrome auto updated to v35, it went back to 'download' file name.
It seems to be linked to this bug/feature. Status: Wontfix.
Use HTML5 download attribute. This attribute will tell browser that virtual link we created is aimed for download only. It will download file from link's href to file with name specified as download attribute's value. This great feature works in Chrome.
window.downloadFile = function(sUrl) {
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined){
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click' ,true ,true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
var query = '?download';
window.open(sUrl + query);
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
Demo Link: http://pixelscommander.com/polygon/downloadjs/#.U4gyDPmSwgS