The process of exporting files
The front-end sends a request, the back-end processes the file stream, and the front-end Blob
parses and downloads it
Implementation process:
Front-end request
Need to change in response to the type arraybuffer
orblob
Not setting the response type will cause the downloaded file to look garbled
responseType: 'arraybuffer'
Take the commonly used request library axios
as an example
get
Request writing
axios.get(url, {
params: form,
responseType: 'arraybuffer'
// responseType: 'blob'
})
post
Request writing
axios.post(url, params, {
responseType: 'arraybuffer'
// responseType: 'blob'
})
Back-end processing returns the file stream
The front end Blob
parses and downloads through the object
The file name and file type are recommended to use the data returned by the backend, which will generally be placed in the response header
File name and type of information stored in content-disposition
andcontent-type
When the file name is Chinese, the back end will generally transcode and the front end can use decodeURIComponent
decoding
Parse and download
According to the structure returned in the above figure, take it axios
as an example, which res
is the parameter of the data returned by the backend after the request is successful.
let filename = decodeURIComponent(
res.headers['content-disposition'].split(';')[1].split('=')[1]
)
// let filename = '导出表格.xlsx' // 可以, 但不建议直接写文件名
let fileType = decodeURIComponent(res.headers['content-type'])
let blob = new Blob([res.data], {
type: fileType
// type: 'application/vnd.ms-excel' // 特殊情况下直接写文件的MIME类型
})
let url = window.URL.createObjectURL(blob)
// 创建一个临时的url指向blob对象
// 创建url之后可以模拟对此文件对象的一系列操作,例如:预览、下载
let a = document.createElement('a')
a.href = url
a.download = filename
// 下载
a.click()
// 释放这个临时的对象url
window.URL.revokeObjectURL(url)