后端直接返回文件的二进制流,前端要用原生JS将其转化为可以下载的文件,试错了不少
最终达到的效果是:
(1)给后端传递一个文件,后端加工后给我返回excel的文件流,前端加工并下载文件
(3)原生的XMLHttpRequest方式代替ajax
(2)文件名用当前日期命名,并下载
记录一下:
后端返回的是这样的东西:
前端使用的是jQuery的AJAX,版本是2.1.4,比较老
因此无法使用方式:
xhrFields: {
responseType: 'blob' // 设置 xhr 的 responseType 为 'blob'
},
也无法直接设置 responseType: 'blob',或者dataType:'blob'
$.ajax({
url: url,
type: "post",
data : formData,
contentType : false,
processData : false,
responseType: "blob",
xhrFields: {
responseType: 'blob' // 设置 xhr 的 responseType 为 'blob'
},
success: function (result) {
//转换为blob
var blob=new Blob([result],{type: 'application/vnd.ms-excel'})
//创建下载的url
let url = window.URL.createObjectURL(blob);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
//下载文件名儿
link.setAttribute("download", "下载明细.xlsx");
//模拟点击事件
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
error: function (data) {
alert(data.msg);
}
});
解决方案:
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status === 200) {
//获取当前日期作为文件名
var currentDate = new Date();
var fileTime = currentDate.toISOString().slice(0, 10)
var blob = xhr.response; // 这就是返回的 Blob 数据
var link = document.createElement("a");
link.style.display = "none";
link.href = window.URL.createObjectURL(blob);
link.setAttribute("download", `${fileTime}_下载明细.xlsx`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else
alert("系统错误");
};
xhr.onerror = function () {
alert("系统错误");
};
xhr.open('POST', 'url', true);
xhr.responseType = 'blob'; // 设置 responseType 为 'blob'
xhr.send(formData);