一、get方式
如果是get请求,可以直接用下面函数访问地址下载
export const downLoadFile = function (url: string) {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.insertBefore(iframe, document.body.lastChild);
};
二、post方式
- 访问 post 请求,注意请求 config 增加配置 { responseType: 'blob' };
- 在请求结束时,可以自行判断返回信息是否是 数据流 决定是否调用下载方法;
/**
*
* @param data post接口响应信息的 data 字段
* @param fileName 下载的文件名
* @param fileType 文件类型 比如表格:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
*
*/
export const downLoadBlob = function (
data: any,
fileType: string,
fileName?: string,
) {
const blob = new Blob([data], {
type: fileType,
});
const objectUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = fileName || String(new Date().getTime());
link.click();
window.URL.revokeObjectURL(objectUrl);
};