[英]Force the browser to download file as CSV from url
我正在從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文件。 請幫幫我。 我們如何強制瀏覽器下載文件。
這里的訣竅是將您的數據轉換為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);
};
使用上面的下載功能。
用法:用兩個參數filename
和content
調用函數下載
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')
}
您在發出請求時應指定正確的Accept標頭。 然后,服務器作為響應,將放置正確的Content-Type標頭。 在您的情況下,您應該在創建XMLHttpRequest時添加此行:
xhttp.setRequestHeader("Accept", "text/csv; charset=utf-8");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.