vue 导出文件功能

生成文件

接口

export const exportFinancialList = (data) => {
    return fetch({
        responseType: 'blob',
        url:EXPORT_FINANCIAL_LIST,
        method:'post',
        data
    })
}

js

exportFinancialList(item).then(res => {
        const blob = new Blob([res]);
        const fileName = "列表.xlsx";
  // 设置文件的名字
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
})

 
遇到的问题 : 下载下来的文件,打开后乱码了

看接口返回的值,像这个样子的

解决办法
 把 const blob = new Blob([res]); 改成 const blob = new Blob([res.data]);

生成压缩包

接口

export const exportData = (data) => {
    return fetch({
        responseType: 'blob',
        url:EXPORT_FINANCIAL_LIST,
        method:'post',
        data
    })
}

js

exportData(params).then(res => {
	 const url = window.URL.createObjectURL(new Blob([res]))
	 var a = document.createElement('a');
     a.href = url;
     a.download = '历史记录.zip';
     a.click();
     window.URL.revokeObjectURL(url)

}).catch(err => {
	console.log(err)
})