87,910
社区成员
发帖
与我相关
我的任务
分享
$.ajax({
type: "POST",
url: .......,
data: {
.......
},
responseType: 'blob',
success: function (response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') != -1) { //判断是否为文件
//var form = $('<form method="POST" action="' + url + '">');
//$.each(params, function (k, v) {
// form.append($('<input type="hidden" name="' + k +
// '" value="' + v + '">'));
//});
//$('body').append(form);
console.log(111);
var fileName = '......xls';
var content = response;
var blob = new Blob([content]);
const elink = document.createElement('a')
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
}
});
$.ajax({
type: "POST",
responseType: 'blob' // 无效
})
是这样设置的
$.ajax({
type: "POST",
xhrFields:{
responseType: 'blob'
}
})
但是$.ajax 不支持接受 responseType 为blob 时的 responseText
源码如下:
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) { // 设置了 responseType 为 blob 或者 arraybuffer 时,这一句报错
responses.text = xhr.responseText;
}
所以使用 $.ajax post 来接受后端返回的流数据无解,不是硬性要求使用 $.ajax 做的话,网上有很多其他解决方法,原生或者axios等。