下载文件常用的几种方式
import axios from "axios"
import * as auth from '@/utils/auth.js'
let ajax = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 100000
});
ajax.interceptors.request.use(config => {
config.headers = {
Authorization: auth.getToken(),
}
return config
},
err => {
return Promise.reject(err)
})
let downloadFile = async (url, formData, options) => {
await ajax.post(url, formData, {responseType: 'arraybuffer'}).then(resp => download(resp, options))
}
let getFile = async (url, options) => {
await ajax.get(url, {responseType: 'blob'}).then(resp => download(resp, options))
}
let download = (resp, options) => {
let blob = new Blob([resp.data], {type: options.fileType ? options.fileType : 'application/octet-binary'})
let href = window.URL.createObjectURL(blob)
downloadBlob(href, options.fileName)
}
let downloadBlob = (blobUrl, fileName, revokeObjectURL) => {
let downloadElement = document.createElement('a')
downloadElement.href = blobUrl
downloadElement.download = fileName
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
if (revokeObjectURL == null || revokeObjectURL) {
window.URL.revokeObjectURL(blobUrl)
}
}
let getDownloadFileUrl = async (url, fileType) => {
let blob
await ajax.get(url, {responseType: 'blob'}).then(resp => {
blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
})
return window.URL.createObjectURL(blob);
}
let getDownloadFileUrlByPost = async (url, data, fileType) => {
let blob
await ajax.post(url, data, {responseType: 'blob'}).then(resp => {
blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
})
return window.URL.createObjectURL(blob);
}
let getDownloadFileBlob = async (url, fileType) => {
let blob
await ajax.get(url, {responseType: 'blob'}).then(resp => {
blob = new Blob([resp.data], {type: fileType ? fileType : 'application/octet-binary'});
})
return blob;
}
export default {
ajax,
downloadFile,
getFile,
getDownloadFileUrl,
getDownloadFileUrlByPost,
getDownloadFileBlob,
downloadBlob
}