后端接口返回:
.zip文件,图片等

.json,.txt文件下载的数据格式:

VUE页面使用
- async downloadFile(fileId: string, fileName: string) {
- try {
- const res = await API.Defect.downloadDefectFile({
- fileId: fileId,
- fileName: fileName
- })
- if (res.data) {
- downloadFetchFiles(res)
- }
- } catch (error) {
- warn(error, true)
- }
- },
downloadFetchFiles方法代码:
- export function downloadFetchFiles(res: { data: BlobPart; fileName: string }) {
- const blob = new Blob([res.data])
- const src = URL.createObjectURL(blob)
- if (src && 'download' in document.createElement('a')) {
- const elink = document.createElement('a')
- elink.download = `${decodeURI(res.fileName)}`
- elink.href = src
- elink.click()
- } else {
- warn('您的浏览器不支持下载功能', true)
- }
- }
这个方法也是常用的文件流下载方式,.txt, .json文件下载后都正常,但是图片,压缩包下载后打不开,后来发现:
注意:在这里需要特别注意的是不管接口是get还是post请求,在请求时需要多加一个参数 responseType:'blob' ,否则等等下载的文件会出现乱码或者下载后打不开文件的问题;
封装接口处添加
-
- /**
- * 下载文件
- */
- export function downloadDefectFile(params: { fileId: string; fileName: string }) {
- return request.get(`/yh/download/downloadForStream?fileId=${params.fileId}&fileName=${params.fileName}`, { responseType: 'blob' })
- }
中午跑通了。