处理后端响应的文件流
// 下载文件
export function downloadFile(stream, filename, filesSuffix) {
console.log("stream instanceof Blob = ", stream instanceof Blob);
let blob = new Blob([stream]);
console.log("blob = ", blob); console.log('blob.type = ', blob.type);
console.log('blob.type === application/octet-stream :', blob.type === 'application/octet-stream')
/*stream必须为流Blob 流类型必须为 application/octet-stream */
if (stream instanceof Blob && blob.type === 'application/octet-stream') {
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url; link.style.display = 'none';
// 解决ie浏览器不支持文件名包含“:”的问题
// const fileName = name + '-' + parseTime(new Date(), '{y}-{m}-{d}') + '.' + suffix
let fileName = ''
if (filename) { fileName = fileName + filename }
if (filesSuffix) { fileName = fileName + filesSuffix }
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link)
} else {
//流内容
let fileReader = new FileReader();
fileReader.onload = function() {
//从内容中获取数据
const res = JSON.parse(this.result);
if (res && (res.code < 200 || res.code > 300)){
//返回res状态异常,抛出原因!
kr.ui.error(res.message || "下载失败!")
}
};
fileReader.readAsText(blob);
}
}