使用a标签访问静态路径请求服务器下载文件时,zip.xlsx等文件类型浏览器打不开会下载到本地, 而image、py、txt、exe在第三方网站上或者跨域项目/前后端部署的,浏览器a标签H5属性download会失 效直接强制打开预览文件,同时低版本ie或者谷歌有兼容性问题
使用file-saves下载文件
//参照
https://blog.csdn.net/m0_67393295/article/details/123220589
//安装
npm install file-saver --save
//request.js
import { saveAs } from 'file-saver'
通用下载方法
export function downFile(url, params, filename, config) {
downloadLoadingInstance = ElLoading.service({
text: '正在下载数据,请稍候', background: 'rgba(0, 0, 0, 0.7)'
})
return service
.get(
url,
{ params: params },
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob',
...config
}
)
.then(async (response) => {
const isLogin = await blobValidate(data)
if (isLogin) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text()
const rspObj = JSON.parse(resText)
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
ElMessage({
message: errMsg,
type: 'error'
})
}
})
.catch((r) => {
console.error(r)
ElMessage({
message: '下载文件出现错误,请联系管理员!',
type: 'error'
})
downloadLoadingInstance.close()
})
}
main.js挂载
app.config.globalProperties.downFile = downFile
在使用的组件
proxy.downFile(opt)