zip文件和xlsx文件
import axios from 'axios'
import { getToken } from '@/utils/auth'const mimeMap = {xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',zip: 'application/zip'
}const baseUrl = process.env.VUE_APP_BASE_API
// zip下载
export function downLoadZip(str, filename) {var url = baseUrl + straxios({method: 'get',url: url,responseType: 'blob',headers: { 'Authorization': 'Bearer ' + getToken() }}).then(res => {resolveBlob(res, mimeMap.zip)})
}
// xlsx文件下载
export function downLoadXlsx(str, filename) {var url = baseUrl + straxios({method: 'get',url: url,responseType: 'blob',headers: { 'Authorization': 'Bearer ' + getToken() }}).then(res => {resolveBlob(res, mimeMap.xlsx)})
}/*** 解析blob响应内容并下载* @param {*} res blob响应内容* @param {String} mimeType MIME类型*/
export function resolveBlob(res, mimeType) {const aLink = document.createElement('a')var blob = new Blob([res.data], { type: mimeType })// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')var contentDisposition = decodeURI(res.headers['content-disposition'])var result = patt.exec(contentDisposition)var fileName = result[1]fileName = fileName.replace(/\"/g, '')aLink.href = URL.createObjectURL(blob)aLink.setAttribute('download', fileName) // 设置下载文件名称document.body.appendChild(aLink)aLink.click()document.body.appendChild(aLink)
}
xml封装通用文件下载
// XML 下载方法
export function xmlDownload( url, method, name) {var xhr = new XMLHttpRequest();xhr.open(method, url, true);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.setRequestHeader("Authorization", "Bearer " + getToken());xhr.send();xhr.responseType = "blob"; // 返回类型blobxhr.onload = function () {let a = document.createElement("a");let blob = new Blob([this.response], {// type: "text/csv;charset=GBK;",type: "application/x-zip;",});let objectUrl = URL.createObjectURL(blob);a.setAttribute("href", objectUrl);a.setAttribute("download", name || 'final_model.xlsx');a.click();}
}
axios封装通用文件下载
import axios from 'axios'
// 创建axios实例
const service = axios.create({// axios中请求配置有baseURL选项,表示请求URL公共部分baseURL: process.env.VUE_APP_BASE_API1,// 超时timeout: 60 * 1000
})// 通用下载方法
export function download(url, params, filename, method) {return service[method || "post"](url, params, {transformRequest: [(params) => {return tansParams(params)}],headers: {'Content-Type': 'application/x-www-form-urlencoded'},responseType: 'blob'}).then((data, header) => {const content = dataconst blob = new Blob([content])if ('download' in document.createElement('a')) {const elink = document.createElement('a')elink.download = filenameelink.style.display = 'none'elink.href = URL.createObjectURL(blob)document.body.appendChild(elink)elink.click()URL.revokeObjectURL(elink.href)document.body.removeChild(elink)} else {navigator.msSaveBlob(blob, filename)}}).catch((r) => {console.error(r)})
}