Javascript 如何使用 window.open 设置文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7034754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:21:30  来源:igfitidea点击:

How to set a file name using window.open

javascriptdownloadwindow.open

提问by huangcd

I'am trying to download temporary result calculated by JavaScript. Say I have a string str, I want to download a file contains strand named it as data.csv, I'm using the following code:

我正在尝试下载由 JavaScript 计算的临时结果。假设我有一个 string str,我想下载一个包含的文件str并将其命名为data.csv,我正在使用以下代码:

window.open('data:text/csv;charset=utf-8,' + str);

The file can be successfully downloaded, but how can I name the file data.csvautomatically rather than set the name by hand each time?

文件可以成功下载,但是如何data.csv自动命名文件而不是每次手动设置名称?

回答by Facebook Staff are Complicit

You can achieve this using the downloadattribute for <a>elements. For example:

您可以使用元素的download属性来实现这一点<a>。例如:

<a href="1251354216241621.txt" download="your-foo.txt">Download Your Foo</a>

This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file.

此属性指示应下载文件(而不是显示,如果适用)并指定应为下载的文件使用哪个文件名。

Instead of using window.open()you could generate an invisible link with the downloadattribute and .click()it.

window.open()您可以使用download属性和.click()它生成一个不可见的链接,而不是使用它。

var str = "Name, Price\nApple, 2\nOrange, 3";
var uri = 'data:text/csv;charset=utf-8,' + str;

var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "data.csv";

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

Unfortunately this isn't supported in all browsers, but adding it won't make things worse for other browsers: they'll continue to download the files with useless filenames. (This assumes that you're using a MIME type is that their browser attempts to download. If you're trying to let the user download an .htmlfile instead of displaying it, this won't do you any good in unsupported browsers.)

不幸的是,并非所有浏览器都支持此功能,但添加它不会使其他浏览器的情况更糟:它们将继续下载带有无用文件名的文件。(这假设您使用的 MIME 类型是他们的浏览器尝试下载。如果您试图让用户下载.html文件而不是显示文件,这在不受支持的浏览器中不会有任何好处。)

回答by Jewel

That does not work in latest Chrome, I have modified that and the following code will work fine,

这在最新的 Chrome 中不起作用,我已经修改了它,下面的代码可以正常工作,

    $("#download_1").click(function() {
    var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
    var json = $.parseJSON(json_pre);

    var csv = JSON2CSV(json);
    var downloadLink = document.createElement("a");
    var blob = new Blob(["\ufeff", csv]);
    var url = URL.createObjectURL(blob);
    downloadLink.href = url;
    downloadLink.download = "data.csv";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
});

So when you click on download_1 id button then it will create an invisible download link and click that. I have used another function to prepare js.

因此,当您单击 download_1 id 按钮时,它将创建一个不可见的下载链接并单击该链接。我已经使用了另一个函数来编写js。

The JSON2CSV function is as follows:

JSON2CSV 函数如下:

function JSON2CSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    var line = '';

    if ($("#labels").is(':checked')) {
        var head = array[0];
        if ($("#quote").is(':checked')) {
            for (var index in array[0]) {
                var value = index + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[0]) {
                line += index + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }

    for (var i = 0; i < array.length; i++) {
        var line = '';

        if ($("#quote").is(':checked')) {
            for (var index in array[i]) {
                var value = array[i][index] + "";
                line += '"' + value.replace(/"/g, '""') + '",';
            }
        } else {
            for (var index in array[i]) {
                line += array[i][index] + ',';
            }
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }
    return str;
}

Hope it will help others :)

希望它会帮助其他人:)

回答by Sameera R.

A shorter version of accepted one (for my case had to use unicode)

接受的较短版本(就我而言,必须使用 unicode)

var link = document.createElement("a");
link.href = 'data:text/csv,' + encodeURIComponent("algún texto");
link.download = "Example.csv";
link.click();

回答by lucas.coelho

A solution for IE is to use msSaveBlob and pass the file name.

IE 的一个解决方案是使用 msSaveBlob 并传递文件名。

For modern browsers solution goes like this, tested: IE11, FF & Chrome

对于现代浏览器,解决方案是这样的,经过测试:IE11、FF 和 Chrome

 var csvData = new Blob([arg.data], {type: 'text/csv;charset=utf-8;'});
        //IE11 & Edge
        if (navigator.msSaveBlob) {
            navigator.msSaveBlob(csvData, exportFilename);
        } else {
            //In FF link must be added to DOM to be clicked
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(csvData);
            link.setAttribute('download', exportFilename);
            document.body.appendChild(link);    
            link.click();
            document.body.removeChild(link);    
        }

There is a good discution about that here

有一个关于一个好discution这里