一、首先是点击下载函数功能
源代码:
```java
const dow = async (record: any) => {
console.log('record',record);
let date: any = {}
date.pcno = record.pcno
date.fileName = record.fileName
date.gmtCreated = dayjs(record.gmtCreated).format('YYYY-MM')
date.importStatus = record.importStatus
date.gmtModified = dayjs(record.gmtModified).format('YYYY-MM')
let response = await dowdan({id:record.id});
console.log('response',response);
let fileName = '报销单' + record.id;
await commonDownloadFile(
response,
// 'application/vnd.ms-excel',
'application/pdf',
fileName,
(f) => {
// message.error(JSON.parse(f)?.errMessage);
},
);
};
二、接下来是封装接口
源代码:
export const dowdan = async (data: any) => {
return request(costControlApi.dowdan, {
method: 'POST',
data,
responseType: 'blob',
// headers: { 'Content-Type': 'application/x-www-form-urlencoded', },
// headers: { 'Content-Type': 'multipart/form-data' },
// requestType: 'form',
})
}
三、然后是接口展示
四、接下来最重要的是对于核心代码下载的前端处理逻辑
源代码:
export const commonDownloadFile = async (file, MIME, name, errorCallback = (val) => { }) => {
console.log('file',file)
try {
// if (file.type !== 'application/json') {
if (window.navigator.msSaveOrOpenBlob) {
// 兼容ie11
const blob = await new Blob([file], { type: MIME })
window.navigator.msSaveOrOpenBlob(blob, `${name}`);
} else {
const blob = await new Blob([file], { type: MIME })
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', name);
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(url); // 释放掉blob对象
}
// } else {
// await blobToString(file, errorCallback)
// }
} catch (e) {
console.error(e)
}
}
整个流程就是这些啦,前端部分处理下载的所有文件在这里就算结束啦~
下面展示下载成果:
点击下载按钮
这个就是整个文件的下载流程啦~