[英]How can I download a file using JQuery Ajax and custom headers?
I am using Laravel Excel to Generate and download files.我正在使用 Laravel Excel 生成和下载文件。 This is my code on the back end:
这是我在后端的代码:
$userExports = new UsersExport($filters);
return $userExports->download();
I can download the file using postman but I am facing issues with jquery because I cannot make the browser start the download to the user.我可以使用邮递员下载文件,但我遇到了 jquery 问题,因为我无法让浏览器开始向用户下载。
This is my jquery code:这是我的 jquery 代码:
url = Settings.AppSettings.Api + "users/export" + queryString;
var settings = {
"async": true,
"url": url,
"method": "GET",
"headers": {
"Authorization": "Bearer " + Session.AuthKey ,
"cache-control": "no-cache",
},
"processData": false,
}
$.ajax(settings).done(function (response) {
// I don't know what to code here.
}).fail(function (response) {
$(".Preloader").fadeOut();
Materialize.toast(response.responseJSON.message, 3000);
if (response.responseJSON.code == 401) {
Session.Logout();
}
});
This is part of the response or file I am getting这是我收到的响应或文件的一部分
PK yOG D X ?[Content_Types].xml MN 0? " %nY vAa (0 ؖg w{&i? @ nbE { y d۸l m X ( ) ? F ;@1_ c)j x/% E y QĿi! K y3 J< Z?1 0?Y L%zV c Ib7 a/l٥P1: q r ?j j0A u "" ( W M )Tj ({ܲ > ?O ,X٭ >B ~ Ӥ6 J= oBZ t X4 Cg , QgmrL ٯc e t Z ? hPv ± u j R } Cv? PK yO 78 K?_rels/.rels j 0 { { 1F ^ʠ 2 l $ -} PK yOG D X ?[Content_Types].xml MN 0? " %nY vAa (0 ؖg w{&i? @ nbE { y d۸l m X ( ) ? F ;@1_ c)j x/% E y QĿi! K y3 J< Z?1 0?Y L%zV c Ib7 a/l٥P1: q r ?j j0A u "" ( W M )Tj ({ > ?O ,X٭ >B ~ Ӥ6 J= oBZ t X4 Cg , QgmrL ٯc e t Z ? hPv ± u j R } Cv? PK yO 78 K?_rels/.rels j 0 { { 1F ^ʠ 2 l $ -}
This is what you need ,这就是你需要的
$.ajax(settings).done(function (response) {
var url = window.URL.createObjectURL(new Blob([response.data]));
var link = document.createElement('a');
var filename = "YourFileName.xls";
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
})
Note : In your ajax setting add response data type as
注意:在您的 ajax 设置中添加响应数据类型为
dataType : 'blob',
Mainly, what it worked was add主要是,它的作用是添加
"xhrFields":{ responseType: 'blob' }, "xhrFields":{ responseType: 'blob' },
I think the problem was that JQuery seems to have TEXT as a default response Type.我认为问题在于 JQuery 似乎将 TEXT 作为默认响应类型。
url = Settings.AppSettings.Api + "users/export" + queryString;
var settings = {
"async": true,
"url": url,
"method": "GET",
"headers": {
"Authorization": "Bearer " + Session.AuthKey ,
"cache-control": "no-cache",
},
"processData": false,
"xhrFields":{
responseType: 'blob'
},
}
$.ajax(settings).done(function (data, textStatus, jqXHR) {
var url = window.URL.createObjectURL(data);
var link = document.createElement('a');
var filename = "Usuarios.xlsx";
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.