| 「这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战」 |
|---|
实际开发中,经常会遇到需要下载的场景:下载本地模板、导出报表等等。下载如何抽取成公共方法么?来来来,代码直接贴出来,下次开发直接拷贝走。
不同文件类型的 type
| 后缀 | MIME Type |
|---|---|
| .doc | application/msword |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| .xls | application/vnd.ms-excel |
| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| .ppt | application/vnd.ms-powerpoint |
| .pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
a标签下载
后端返回一个可下载的url文件,或者前端本地保存的文件,通过路径引入下载。
// 本地资源下载,引入路径即可,这里的路径指的是打包后文件与代码文件的相对路径
<a href="./import-template.xlsx" download target="_blank"> 下载上传模板 </a>
下载存在前端的静态文件
- 静态资源文件一般放置在
public的static的目录下,打包后随一起上传自服务器
下载静态文件的公用方法
downloadLocalFile(url,name){
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.target = '_blank'
const fileName = name || url.substring(url.lastIndexOf('/') + 1)
link.setAttibute('download', fileName)
document.body.appendChild(link)
link.click() //下载完成移除元素
document.body.removeChild(link)
},
// 使用
download(下载文件地址,文件名)
页面中调用
// @click="download(下载文件名,文件名)"
<el-button type="text" @click="download('/public/files/test.xls','template.xls')">下载</el-button>
下载后台返回的流文件
请求后台流文件时一要记得添加responseType: "blob"
- 请求后台下载接口
/**
* 下载文件 用于excel导出
* @param url
* @param parameter
* @returns {*}
*/
export function downFile(url,data){
return axios({
url,
data,
method:'post' ,
responseType: 'blob'
})
}
下载文件公共方法
/**
* 下载文件
* @param url 后台下载api
* @param params 下载参数
* @param fileName 下载文件名
* @returns {*}
*/
export function downloadFiles(url,params,fileName='download.xls') {
return downFile(url, params).then((data) => {
// 判断流文件是否存在
if (!data || data.size === 0) {
Vue.prototype['$message'].warning('文件下载失败')
return
}
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(new Blob([data]), fileName)
} else {
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link) //下载完成移除元素
window.URL.revokeObjectURL(url) //释放掉blob对象
}
})
}