【问题标题】:how to download a file on Chrome without auto renaming file to "download"?如何在 Chrome 上下载文件而不自动将文件重命名为“下载”?
【发布时间】:2014-05-29 17:35:57
【问题描述】:

我使用 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,它又回到了“下载”文件名。

【问题讨论】:

  • 您使用的是哪个版本的 Chrome?下载属性应该支持回到 v31:caniuse.com/#feat=download
  • 如果您已经在使用另一个问题中建议的解决方案之一,并且它不再适用于新的 Chrome 版本,那么您应该提前提及。
  • 似乎是下载属性的错误,您应该在code.google.com/p/chromium/issues/list报告错误

标签: javascript jquery html google-chrome


【解决方案1】:

它似乎与this bug/feature 相关联。状态:不会修复。

【讨论】:

    【解决方案2】:

    使用 HTML5 下载属性。该属性将告诉浏览器我们创建的虚拟链接仅用于下载。它将文件从链接的 href 下载到名称指定为下载属性值的文件。这个很棒的功能可以在 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;
    

    演示链接:http://pixelscommander.com/polygon/downloadjs/#.U4gyDPmSwgS

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      相关资源
      最近更新 更多