前端下载文件流,如下是图片说明
下面是代码
//这是请求时的处理参数
xhrRequest({
url: "http://172.30.16.40:8123/api/bomplus?SAP_BillId=0400004143",
method: 'get',
headers: {
'Content-Type': 'application/json'
},
responseType: 'blob',
data: {},
})
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
//-------------------------
//这是文件流处理的代码
downloadFileNew: function (res) {
console.log(res);
if (res.status != 200) {
Message.error(decodeURIComponent(res.request.statusText));
return false;
} else {
let blob = new Blob([res.request.response], { type: res.headers['content-type'] });
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
document.body.appendChild(a);
let fileName = res.headers['content-disposition'].split(';')[1].split('=')[1];
if (fileName[0] == '"') {
fileName = fileName.split('"')[1];
}
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
},
图中显示文件流的下载没有问题,问题是最后文件打开的时候wps提示 无法打开文件 ,但是postman的send and Download下载的文件没有问题,网上也找了很多参考,但大部分都是说mockjs导致的,但是我这个项目里面没有mock,所以返回的request是没有问题的,其中blob格式也设置了。请各位前端能人志士尽情的提出意见,本人不胜感激!
看截图感觉接口返回数据有问题。指定了responseType:'blob',response应该是blob数据类型,怎么存储的还是字符串一样的内容。
题主是不是将Excel文件用io当字符串读出后输出了?应该是输出2进制的数据。
直接浏览器访问接口后保存文件,这个文件能打开吗?
文件怎么能是
headers: {
'Content-Type': 'application/json'
},
用ostream啊
<script>
$(document).ready(function () {
$('#btn1').click(function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "HandlerDownFile.ashx?fileName=test.txt", true);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
var a = document.createElement('a');
a.download = "test.txt";
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
};
xhr.send();
});
})
如果返回的本身是一个文件,就不需要new blob了
ok