方式一
1.封装方法
export const download =(res,type, filename)//创建blob对象,解析流数据
const blob =new Blob([res.data],{
// type:'application/pdf;charset=UTF-8’表示下载文档为pdf,如果是word则设置为msword,excel为exceltype:type
})
// const filename = res.headers['content-disposition'].split(';')[1].split('filename=')[1] // 获取文件名
// 创建a标签,用于模拟点击事件
const downloadElement = document.createElement('a')
//兼容webkix浏览器,处理webkit浏览器中href自动添加b1ob前缀,默认在浏览器打开而不是下载
const URL =window.URL.createObiectURL(blob)
//根据解析后的blob对象创建URL对象
const href = URL.createObjectURL(blob)
//下载链接
downloadElement.href=href
//下载文件名,如果后端没有返回,可以自己写a.download ='文件.pdf'
downloadElement.download = decodeURIComponent(filename)// decodeURIComponent防止中文乱码
document.body.appendChild(downloadElement)
//点击a标签,进行下载
downloadElement.click()
//收尾工作,在内存中移除URL 对象
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
}
2.如何使用
const downloadFile = async () => {
const result = await $download()
download(result.data,"application/vnd.ms-excel','代码统计.x1sx')
}
方式二
1.封装 htpp 中方法
/**
* download
* @param {string} url
* @param {object} option
*/
static download = (option: HttpOption) => {
return this.Request('get', {
successToast: false,
errorToast: false,
returnHttpData: true,
noCheckCode: true,
otherAxiosOption: { responseType: 'blob' },
...option
}).then((res) => {
if (res) {
const { headers } = res || {};
const contentDisposition = headers?.['content-disposition'];
let fileName = '文件下载';
if (contentDisposition) {
fileName = decodeURIComponent(
contentDisposition?.split(';')?.[1]?.split('filename=')?.[1] || ''
);
}
downloadFile(res.data, fileName);
return {};
}
});
};
2.下载文件方法
/**
* 下载文件
* @param content 文件内容
* @param fileName 文件名
*/
export function downloadFile(content: string, fileName: string) {
var aLink = document.createElement('a');
var blob = new Blob([content]);
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
}
3.如何使用
export const exportPDFApi = async (data?: any): Promise<any> =>
await $download({
url: `${API_FIX}/view/layout/exportPDF`,
data: data
});
import { exportPDFApi } from '@/api/***';
const exportPdfFn = (isDesp: boolean) => {
exportPDFApi({
layoutName: pdfTitle.value,
imagePath: imgPath.value,
content: pdfContent.value,
isDesc: isDesp ? 1 : 0,
});
}
常用base64常用的前缀(excel,doc,pdf,png,jpg)
.doc——data:application/msword;base64,
.docx——data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,
.xls——data:application/vnd.ms-excel;base64,
.xlsx——data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,
.pdf——data:application/pdf;base64,
.ppt——data:application/vnd.ms-powerpoint;base64,
.pptx——data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,
.txt——data:text/plain;base64,
.png——data:image/png;base64,
.jpg——data:image/jpeg;base64,
.gif——data:image/gif;base64,
.svg——data:image/svg+xml;base64,
.ico——data:image/x-icon;base64,
.bmp——data:image/bmp;base64,