1. 问题描述
最近在文件下载时遇到了一点小问题:使用 apifox/postman 等客户端下载文件时,可以正常下载,但是使用 apifox 等网页端(或者浏览器端)下载时出现无法下载或者下载后无法正常打开的问题,当我使用 Firefox 浏览器下载时又可以正常下载,而 Chromium 内核浏览器却无法正常下载,如果前端代码没有问题的话这种情况大概率是后端的问题,所以可以和服务端(后端)进行一定的协商。
2. 下载方式
2.1 form 表单方式
/**
* Form表单提交 Post
* @param {*} url
* @param {*} paramsName
* @param {*} param
*/
export const FormForPost = (url, paramsName, param) => {
// 创建表单,设置表单提交方式
const form = document.createElement('form')
form.action = url
form.method = 'post'
form.style.display = 'none'
const input = document.createElement('input')
input.name = paramsName
input.value = JSON.stringify(param)
form.appendChild(input)
const button = document.createElement('input')
button.type = 'button'
form.appendChild(button)
document.body.appendChild(form)
form.submit()
document.body.removeChild(form)
}
/**
* Form表单提交 Get
* @param {*} url
*/
export const FormForGet = url => {
// 创建表单,设置表单提交方式
const form = document.createElement('form')
form.action = url
form.method = 'get'
form.style.display = 'none'
const button = document.createElement('input')
button.type = 'button'
form.appendChild(button)
document.body.appendChild(form)
form.submit()
document.body.removeChild(form)
}
2.2 blob 流
export const downloadUpdate = async (url, paramsName, data) => {
try {
const response = await post2(url, {
name: paramsName,
data,
responseType: 'blob'
// headers: {
// 'content-type': 'application/octet-stream;charset=UTF-8'
// }
})
// window.console.log('download: ', response)
// { type: 'application/octet-stream;charset=UTF-8' }
return new Blob([response.data])
} catch (error) {
console.error('Error:', error)
throw error // 可以选择抛出异常以供进一步处理
}
}
async processExportListOfLiuZhou(data) {
const url = this.$store.getters._URL
const fileContent = await downloadUpdate(
`${url}/sample/process/file/download`,
'request',
data
)
const blobUrl = window.URL.createObjectURL(fileContent)
const link = document.createElement('a')
link.href = blobUrl
link.setAttribute('download', data.fileName)
document.body.appendChild(link)
link.style.display = 'none'
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(url)
}
2.3 file-saver
import { saveAs } from 'file-saver'
const url = this.$store.getters._URL
const fileContent = await downloadUpdate(
`${url}/sample/process/file/download`,
'request',
data
)
saveAs(fileContent, data.fileName)