由于最近开发的项目老是遇到文件流下载预览的问题,因此做一个总结:
关键代码:
async previewFile(file) {
if (file && file.response && file.response.success) {
// 这个接口返回的是个文件流,有一个主意点就是,接收流文件的 responseType 要设置为 "blob"
// request.get(Api.DOWNLOADFILE + "/" + fileId, {
// responseType: "blob",
// });
const respBlob = await downloadFile(file.response.data.id);
let blob = new Blob([respBlob], { type: file.type });
const a = document.createElement("a");
const fileName = file.name;
if ("download" in a) {
// 不是IE浏览器
// 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
const URL = window.URL || window.webkitURL;
// 根据解析后的blob对象创建URL 对象
const herf = URL.createObjectURL(blob);
// 下载链接
a.href = herf;
// 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// 在内存中移除URL 对象
window.URL.revokeObjectURL(herf);
} else {
// IE 10+
const wn = window.navigator as any;
wn.msSaveBlob(blob, fileName);
}
}
},
注意!
接收流文件的 responseType 要设置为 "blob"
request.get(Api.DOWNLOADFILE + "/" + fileId, {
responseType: "blob",
});
完整的ant-design 自定义预览文件代码如下:
html 部分代码
<a-upload
name="file"
accept=".pdf,.png,.jpg"
:action="`${upload}`"
:headers="uploadHeaders"
:file-list="fileList"
@change="handleChange"
:beforeUpload="beforeUpload"
@preview="previewFile"
>
<a-button class="margin-clear" :disabled="editDisable">
<a-icon type="upload" /> 点击上传文件
</a-button>
<span class="explain ml20">支持上传png、jpg格式的图片或PDF</span>
</a-upload>
js 部分代码
data(){
return {
fileList: [],
}
},
method: {
handleChange({ file, fileList }) {
this.fileList = fileList;
},
async previewFile(file) {
if (file && file.response && file.response.success) {
const respBlob = await downloadFile(file.response.data.id);
let blob = new Blob([respBlob], { type: file.type });
const a = document.createElement("a");
const fileName = file.name;
if ("download" in a) {
// 不是IE浏览器
// 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
const URL = window.URL || window.webkitURL;
// 根据解析后的blob对象创建URL 对象
const herf = URL.createObjectURL(blob);
// 下载链接
a.href = herf;
// 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// 在内存中移除URL 对象
window.URL.revokeObjectURL(herf);
} else {
// IE 10+
const wn = window.navigator as any;
wn.msSaveBlob(blob, fileName);
}
}
},
beforeUpload(file: any, fileList: any) {
if (fileList && fileList.length >= 3) return false;
const isLt20M = file.size / 1024 / 1024 <= 30;
if (!isLt20M) {
this.$message.error("文件大小不能超过30MB!");
return false;
}
return true;
},
}