如何在Chrome上下载文件而不将文件自动重命名为“下载”

how to download a file on Chrome without auto renaming file to "download"?

本文关键字:下载 文件 重命名 命名为 Chrome      更新时间:2023-09-26

我使用javascript生成文件并下载。看起来,根据chrome的版本,下载文件名可以自动重命名为"下载"。有办法避免吗?

这是我的代码:

var link = document.createElement("a");
link.setAttribute("href", 'data:application/octet-stream,' + 'file content here');
link.setAttribute("download", 'file1.txt');
link.click();

这不是一个重复的问题,因为我使用的是最新的Chrome,之前建议的超链接正是我正在使用的。我认为,Chrome v34工作得很好,但一旦我的Chrome自动更新到v35,它又回到了"下载"文件名。

似乎与这个bug/特性有关。状态:Wontfix。

使用HTML5下载属性。这个属性将告诉浏览器,我们创建的虚拟链接仅用于下载。它将下载文件从链接的href到文件名指定为下载属性的值的文件。

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链接:http://pixelscommander.com/polygon/downloadjs/#.U4gyDPmSwgS