简体   繁体   English

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

[英]How to set a file name using window.open

I'am trying to download temporary result calculated by JavaScript.我正在尝试下载由 JavaScript 计算的临时结果。 Say I have a string str , I want to download a file contains str and named it as data.csv , I'm using the following code:假设我有一个字符串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.csv automatically rather than set the name by hand each time?文件可以成功下载,但是如何自动命名文件data.csv而不是每次手动设置名称?

You can achieve this using the download attribute for <a> elements.您可以使用<a>元素的download属性来实现这一点。 For example:例如:

<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 download attribute and .click() it.您可以使用download属性和.click()生成一个不可见的链接,而不是使用window.open()

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 .html file instead of displaying it, this won't do you any good in unsupported browsers.) (这假设您使用的 MIME 类型是他们的浏览器尝试下载。如果您试图让用户下载.html文件而不是显示它,这在不受支持的浏览器中没有任何好处。 )

That does not work in latest Chrome, I have modified that and the following code will work fine,这在最新的 Chrome 中不起作用,我已经修改了它,下面的代码可以正常工作,

 $("#download_1").on('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.因此,当您单击 download_1 id 按钮时,它将创建一个不可见的下载链接并单击该链接。 I have used another function to prepare js.我已经使用了另一个函数来编写js。

The JSON2CSV function is as follows: JSON2CSV 函数如下:

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

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

        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 :)希望它会帮助其他人:)

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();

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这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM