强制浏览器从URL下载文件为CSV

时间:2017-05-29 06:27:56

标签: javascript csv

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

所需的回复标题:

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

当前回复标题

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')
}

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

2 个答案:

答案 0 :(得分:2)

这里的诀窍是将您的数据转换为blob并使用blob url模拟锚标记上的click事件。

var blob = new Blob([content]);

创建点击事件

var evnt =  new Event('click');

然后创建一个锚标记,如下所示,并发送事件

  $("<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);
};

使用上述下载功能。

USAGE:使用两个参数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')
}

答案 1 :(得分:-1)

您在发出请求时应指定正确的Accept标头。然后,服务器作为响应,将放置正确的Content-Type标头。在您的情况下,您应该在创建XMLHttpRequest时添加此行:

xhttp.setRequestHeader("Accept", "text/csv; charset=utf-8");