10

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.

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
user3688566
  • 101
  • 1
  • 4
  • What version of Chrome are you using? The download attribute should have support going back to v31: http://caniuse.com/#feat=download – anotherdave May 29 '14 at 17:46
  • If you were already using one of the solutions suggested in the other question, and it is just not working anymore with a new Chrome version, then you should have mentioned that upfront. – CBroe May 29 '14 at 21:59
  • Seems like a bug with the download attribute, you should report a bug at https://code.google.com/p/chromium/issues/list – Fabrício Matté May 30 '14 at 01:57

2 Answers2

2

It seems to be linked to this bug/feature. Status: Wontfix.

user3147646
  • 131
  • 1
  • 5
1

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

Skwal
  • 2,160
  • 2
  • 20
  • 30
Vishal
  • 171
  • 7