![](/img/trans.png)
[英]Using Javascript to add custom http header and trigger file download
[英]How to set a header for a HTTP GET request, and trigger file download?
更新 20140702:
(但我將其他答案標記為接受而不是我自己的答案,因為它讓我在那里一半,並獎勵努力)
似乎無法通過與<a href="...">
鏈接設置HTTP請求標頭,並且只能使用XMLHttpRequest
完成。
但是,鏈接到的URL是應該下載的文件(瀏覽器不應該導航到它的URL),我不確定這是否可以使用AJAX完成。
此外,返回的文件是二進制文件,而AJAX不適用於此。
如何使用添加了自定義標頭的HTTP請求觸發文件下載?
編輯:修復損壞的鏈接
有兩種方法可以下載 HTTP請求要求設置標頭的文件 。
第一個的功勞歸於@ guest271314,第二個功能歸功於@dandavis。
第一種方法是使用HTML5 File API創建臨時本地文件,第二種方法是將base64編碼與數據URI結合使用。
我在項目中使用的解決方案對小文件使用base64編碼方法,或者在File API不可用時使用,否則使用File API方法。
解:
var id = 123;
var req = ic.ajax.raw({
type: 'GET',
url: '/api/dowloads/'+id,
beforeSend: function (request) {
request.setRequestHeader('token', 'token for '+id);
},
processData: false
});
var maxSizeForBase64 = 1048576; //1024 * 1024
req.then(
function resolve(result) {
var str = result.response;
var anchor = $('.vcard-hyperlink');
var windowUrl = window.URL || window.webkitURL;
if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
var blob = new Blob([result.response], { type: 'text/bin' });
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', id+'.bin');
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
else {
//use base64 encoding when less than set limit or file API is not available
anchor.attr({
href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
download: id+'.bin',
});
anchor.get(0).click();
}
}.bind(this),
function reject(err) {
console.log(err);
}
);
請注意,我沒有使用原始XMLHttpRequest
,而是使用ic-ajax ,並且應該與jQuery.ajax
解決方案非常相似。
另請注意,您應該將text/bin
和.bin
替換為與下載的文件類型相對應的內容。
可以在此處找到 FormatUtils.utf8toBase64
的實現
嘗試
HTML
<!-- placeholder ,
`click` download , `.remove()` options ,
at js callback , following js
-->
<a>download</a>
JS
$(document).ready(function () {
$.ajax({
// `url`
url: '/echo/json/',
type: "POST",
dataType: 'json',
// `file`, data-uri, base64
data: {
json: JSON.stringify({
"file": "data:text/plain;base64,YWJj"
})
},
// `custom header`
headers: {
"x-custom-header": 123
},
beforeSend: function (jqxhr) {
console.log(this.headers);
alert("custom headers" + JSON.stringify(this.headers));
},
success: function (data) {
// `file download`
$("a")
.attr({
"href": data.file,
"download": "file.txt"
})
.html($("a").attr("download"))
.get(0).click();
console.log(JSON.parse(JSON.stringify(data)));
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
});
我正在添加另一種選擇。 上面的答案對我來說非常有用,但我想使用jQuery而不是ic-ajax(當我嘗試通過bower安裝時,它似乎與Ember有依賴關系)。 請記住,此解決方案僅適用於現代瀏覽器。
為了在jQuery上實現這一點,我使用了jQuery BinaryTransport 。 這是一個很好的插件來讀取二進制格式的AJAX響應。
然后你可以這樣做下載文件並發送標題:
$.ajax({
url: url,
type: 'GET',
dataType: 'binary',
headers: headers,
processData: false,
success: function(blob) {
var windowUrl = window.URL || window.webkitURL;
var url = windowUrl.createObjectURL(blob);
anchor.prop('href', url);
anchor.prop('download', fileName);
anchor.get(0).click();
windowUrl.revokeObjectURL(url);
}
});
上述腳本中的變量意味着:
$('a.download-link')
。 我想在這里發布我的解決方案,這是完成AngularJS,ASP.NET MVC。 該代碼說明了如何使用身份驗證下載文件。
WebApi方法和輔助類:
[RoutePrefix("filess")]
class FileController: ApiController
{
[HttpGet]
[Route("download-file")]
[Authorize(Roles = "admin")]
public HttpResponseMessage DownloadDocument([FromUri] int fileId)
{
var file = "someFile.docx"// asking storage service to get file path with id
return Request.ReturnFile(file);
}
}
static class DownloadFIleFromServerHelper
{
public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
{
var result = request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(file)
};
return result;
}
}
Web.config文件更改為允許在自定義標頭中發送文件名。
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
<add name="Access-Control-Allow-Origin" value="*" />
Angular JS服務部分:
function proposalService($http, $cookies, config, FileSaver) {
return {
downloadDocument: downloadDocument
};
function downloadFile(documentId, errorCallback) {
$http({
url: config.apiUrl + "files/download-file?documentId=" + documentId,
method: "GET",
headers: {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer " + $cookies.get("api_key")
},
responseType: "arraybuffer"
})
.success( function(data, status, headers) {
var filename = headers()['x-filename'];
var blob = new Blob([data], { type: "application/octet-binary" });
FileSaver.saveAs(blob, filename);
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
errorCallback(data, status);
});
};
};
FileUpload的模塊依賴:angular-file-download(gulp install angular-file-download --save)。 注冊如下所示。
var app = angular.module('cool',
[
...
require('angular-file-saver'),
])
. // other staff.
純粹的jQuery。
$.ajax({
type: "GET",
url: "https://example.com/file",
headers: {
'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
},
xhrFields: {
responseType: 'blob'
},
success: function (blob) {
var windowUrl = window.URL || window.webkitURL;
var url = windowUrl.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.href = url;
anchor.download = 'filename.zip';
anchor.click();
anchor.parentNode.removeChild(anchor);
windowUrl.revokeObjectURL(url);
},
error: function (error) {
console.log(error);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.