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

标签 javascript csv

我正在从 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/

相关文章:

javascript - nodejs和MongoDB的collection.find()没有响应

Javascript函数调整窗口高度和宽度

python - 来自字符串输出的 CSV 文件

Java - JFrame 保存多行

java - ArrayIndexOutOfBoundsException - 解析 csv 文件时

javascript - 在 Javascript 中从字符串(从数组)中删除

javascript - 主干是否对集合中的所有元素或仅添加的元素进行排序

javascript - 关于 Handsontable 条件格式

python - 使用 CSV 数据 python 创建条形图

r - 有没有办法将具有不同行长度的 csv 文件扫描到列表中?