特别说明:请求时参数的配置,请结合不同框架的配置,随机应变(例:isReturnNativeResponse: true),封装方式不同,使用不同!
封装的api
// post
export const indicatorTempDown = (params) =>
defHttp.post(
{
url: Api.enterprisePageExport,
params,
// headers: { Authorization: '***' },
responseType: 'blob',
},
// 不可缺少(框架自定义属性)(是否返回本机响应头 例如:当你需要获取响应头时使用这个属性)
{ isReturnNativeResponse: true },
);
// get
export const indicatorTempDown = () =>
defHttp.get(
{ url: Api.indicatorTempDown, responseType: 'blob' },
// 不可缺少(框架自定义属性)(是否返回本机响应头 例如:当你需要获取响应头时使用这个属性)
{ isReturnNativeResponse: true },
);
局部逻辑
async function downModel() {
let res = await indicatorTempDown();
// 调用下载方法
downloadByData(res.data, '模板.xlsx');
}
实际调用的文件流下载
/**
* Download according to the background interface file stream
* @param {*} data
* @param {*} filename
* @param {*} mime
* @param {*} bom
*/
export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
const blobURL = window.URL.createObjectURL(blob);
const tempLink = document.createElement('a');
tempLink.style.display = 'none';
tempLink.href = blobURL;
tempLink.setAttribute('download', filename);
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
window.URL.revokeObjectURL(blobURL);
}