Front-end export excel file download file

The process of exporting files

The front-end sends a request, the back-end processes the file stream, and the front-end Blobparses and downloads it

Implementation process:

Front-end request

Need to change in response to the type arraybufferorblob
Not setting the response type will cause the downloaded file to look garbled
responseType: 'arraybuffer'
Take the commonly used request library axiosas an example

getRequest writing

axios.get(url, {
    
    
  params: form,
  responseType: 'arraybuffer'
  // responseType: 'blob'
})

postRequest writing

axios.post(url, params, {
    
    
  responseType: 'arraybuffer'
  // responseType: 'blob'
})

Back-end processing returns the file stream

Insert picture description here

The front end Blobparses 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

Insert picture description here
File name and type of information stored in content-dispositionandcontent-type

When the file name is Chinese, the back end will generally transcode and the front end can use decodeURIComponentdecoding
Parse and download
According to the structure returned in the above figure, take it axiosas an example, which resis 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)

注意

1. filename 可以直接赋值一个字符串包含文件后缀名, 例如: ('导出表格.xlsx'), 但建议从响应头取
2. new Blob() 的第一个参数为一个数据序列,可以是任意格式的值,例如,任意数量的字符串,Blobs 以及 ArrayBuffers , 不一定是 res.data , 也可能是 res.body 或其它, 具体根据后端的返回来写
3. new Blob() 的第二个参数用于指定将要放入 Blob 中的数据的类型 (MIME) , 大多数情况从响应头取, 但是后端返回 ( content-type: application/octet-stream 是默认的未知的类型, 除非你知道具体是什么类型,否则解析不出来 ) 的时候需要自己手动设置 MIME 类型。 例如: Excel 表需设置成 { type: 'application/vnd.ms-excel' }

MIME type reference for multiple file types click here

Guess you like

Origin blog.csdn.net/zty867097449/article/details/115297643