gpt4 book ai didi

javascript - 强制浏览器从 url 下载 CSV 文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:25:46 26 4
gpt4 key购买 nike

我正在从 URL 下载 CSV 文件,如何设置某些响应 header 以下载我的文件

所需的响应 header :

HTTP/1.1 200 OK
Date: Mon, 29 May 2017 06:03:38 GMT
Content-Type: application/octet-stream
Content-Length: 340
Connection: keep-alive
Expires: Tue, 03 Jul 2001 06:00:00 GMT
Last-Modified: Mon May 29 11:33:38 IST 2017
Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Pragma: no-cache
Content-Disposition: attachment; filename="5756913MerchantTransactionFile20170529113338.csv"
Server: Some
Access-Control-Allow-Origin:
Access-Control-Allow-Origin:
authorized: true
authorizehtml: true

当前响应 header

HTTP/1.1 200 OK
Date: Mon, 29 May 2017 06:16:52 GMT
Server: Apache/2.4.18 (Unix) PHP/5.5.36
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
Access-Control-Max-Age: 1000
Access-Control-Allow-Headers: x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Expires: Tue, 03 Jul 2001 06:00:00 GMT
Last-Modified: Mon May 29 11:46:52 IST 2017
Cache-Control: no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: application/json
Content-Length: 0
Keep-Alive: timeout=5, max=97
Connection: Keep-Alive

我的代码:

openFile(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

}
};
xhttp.open("GET",url, true);
xhttp.send();
//window.open(url, '_blank')
}

正在尝试从 url 下载 csv 文件。请帮帮我。我们如何强制浏览器下载文件。

最佳答案

这里的技巧是将您的数据转换为 blob,并在带有 blob url 的 anchor 标记上模拟点击事件。

var blob = new Blob([content]);

创建点击事件

var evnt =  new Event('click');

然后如下创建 anchor 标签并分发事件

  $("<a>", {
download: filename,
href: webkitURL.createObjectURL(blob)
}).get(0).dispatchEvent(evnt);

这是一个函数

 var download = function(filename, content) {
var blob = new Blob([content]);
var evnt = new Event('click');

$("<a>", {
download: filename,
href: webkitURL.createObjectURL(blob)
}).get(0).dispatchEvent(evnt);
};

使用上面的下载功能。

用法:使用两个参数 filenamecontent 调用函数下载

openFile(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(data) {
if (this.readyState == 4 && this.status == 200) {
download('file.csv', data);
}
};
xhttp.open("GET", url, true);
xhttp.send();
//window.open(url, '_blank')
}

关于javascript - 强制浏览器从 url 下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com