前端请求设置 responseType: “blob”
后台接口返回的文件流如下:
拿到后端返回的文件流后:
预览
<iframe :src="previewUrl" frameborder="0" style="width: 500px; height: 500px;"></iframe>
1、预览
view(data) {
// 文件类型
let fileType = this.fileName.slice(this.fileName.length - 3).toUpperCase();
let myBlob = '';
//不同文件类型设置不同的type
if (fileType == 'PDF') {
myBlob = new window.Blob([data], { type: 'application/pdf' });
} else {
myBlob = new window.Blob([data], { type: 'image/png' });
}
const previewUrl = window.URL.createObjectURL(myBlob);
this.previewUrl = previewUrl;// iframe预览
// window.open(previewUrl, '_blank');// 浏览器新打开窗口
},
2、下载
// 下载
downFile() {
var data = this.fileData;
var fileType = this.fileName.slice(this.fileName.length - 3).toUpperCase();
var blob = "";
if (fileType == 'PDF') {
blob = new window.Blob([data], { type: 'application/pdf' });
} else if (fileType == 'PNG') {
blob = new window.Blob([data], { type: 'image/png' });
}
const a = document.createElement("a");
const objectUrl = URL.createObjectURL(blob);
a.setAttribute("href", objectUrl);
a.setAttribute("download", this.fileName);
a.click();
URL.revokeObjectURL(a.href); // 释放url
}