axios 上传 和下载 excel 文件
-
上传 excel 文件
-
axios 请求配置
import axios from 'axios' // 导入(校验数据) export const postFile = (data) => { return axios.post({ url: `上传地址`, data, headers: { 'Content-Type': 'multipart/form-data' } }) }
-
调用方法处
// 上传文件校验 const uploadCheck = async () => { try { const file = new FormData() file.append('file', importFile.value) // 调用后端对应的接口 const res = await postFile(file) } catch (error) { console.log('error', error) } }
-
-
下载 excel 文件
-
axios 请求
import axios from 'axios' // 导入模板下载 export const downloadFile = () => { return axios.post({ url: `后端下载地址`, responseType: 'blob' // 指定响应类型为 blob }) }
-
调用方法处
const downLoadFileHandle = async () => { try { const res = await downloadFile() if (res) { exportExcel(res, '模板') } } catch (error) { console.log(error) } } /** * 二进制流转excel下载 * @param tSource * @returns */ export const exportExcel = function (blob: Blob, name?: string) { const url = window.URL.createObjectURL(new Blob([blob], { type: "application/octet-stream;charset=UTF-8" })) const link = document.createElement('a'); link.href = url; link.setAttribute('download', name + '.xls'); // 设置文件名 document.body.appendChild(link); link.click(); // 模拟点击下载文件 document.body.removeChild(link); // 下载完成后移除元素 window.URL.revokeObjectURL(url); // 释放URL对象 }
-