1. Initiate the interface to request the binary file stream saved in the background
import axios from 'axios'
import { getToken } from '@/utils/auth'
const mimeMap = {
word: 'application/msword; application/vnd.openxmlformats-officedocument.wordprocessingml.document; '.pdf: 'application/pdf'.xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'.zip: 'application/zip'
}
const baseUrl = process.env.VUE_APP_BASE_API;
export function downLoadZip(str, filename) {
var url = baseUrl + str
axios({
method: 'get'.url: url,
responseType: 'blob'.headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res= > {
resolveBlob(res, mimeMap.zip)
})
}
Copy the code
Parse the bloB data of the response
/** * Parse the blob response content and download *@param {*} Res blob Response contents *@param {String} MimeType MIME type */
export function resolveBlob(res, mimeType) {
const aLink = document.createElement('a')
var blob = new Blob([res.data], { type: mimeType })
Responsetheader (" content-disposition ", "attachment; Filename =xxxx.docx") set filename;
var pattern = new RegExp('filename=([^;] + \ \ [^ \ \.;] +); * ')
var contentDisposition = decodeURI(res.headers['content-disposition'])
var result = pattern.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g.' ')
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // Set the name of the downloaded file
document.body.appendChild(aLink)
aLink.click()
document.body.appendChild(aLink)
}
Copy the code