javascript - how to download a file on Chrome without auto renaming file to "download"? -
i use javascript generate file , download it. seems, depending on version of chrome, download file names can auto renamed 'download'. there way avoid it?
this code:
var link = document.createelement("a"); link.setattribute("href", 'data:application/octet-stream,' + 'file content here'); link.setattribute("download", 'file1.txt'); link.click();
this not duplicated question, because i'm using latest chrome , suggested hyperlink i'm using. think, chrome v34 works fine, once chrome auto updated v35, went 'download' file name.
use html5 download attribute. attribute tell browser virtual link created aimed download only. download file link's href file name specified download attribute's value. 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. prevent file 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 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
Comments
Post a Comment