第一种
<div class="item2" @click="handleDownloadFile('文件地址','haohaohao')">下载</div>
// 下载模版
handleDownloadFile (url, name) {
if (!url) {
this.$message.error('暂无文件')
return false
}
// 此方法会不带后缀名,所以要拿到文件的后缀名
const num = url.split('.')
const type = num[num.length - 1]
const link = document.createElement('a')
fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
link.href = URL.createObjectURL(blob)
link.download = `${name}.${type}` // 此处的name是下载的名称
document.body.appendChild(link)
link.click()
})
}
第二种
页面引入方式
// 方法引到页面
import { staticFileDownload } from '@/utils/index'
// 下载方法
staticFileDownload('文件地址', '名称')
export const staticFileDownload = (href, filename = '文件下载', fileType = 'xlsx') => {
if (!href) {
vm.$message.error('未发现文件,请检查');
return;
}
var a = document.createElement("a"); //创建一个a标签
a.href = href; // 给a标签的href属性值加上地址,如果是项目本地文件,写绝对路径 例如:/static/模板.xlsx
a.download = `${filename}.${fileType}`; //设置下载文件的文件名,这里加上.xlsx指定文件类型,pdf文件就指定.pdf即可
a.style.display = "none"; // 隐藏a标签
document.body.appendChild(a); // 将a标签追加到文档对象中
a.click(); // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
a.remove(); // 一次性的,用完就删除a标签
}
第三种文件流下载
页面引入方法
import { exportExcel } from '@/utils/index'
调用方法
exportExcel(res,'名称')
// 导出Excel、zip压缩文件
export const exportExcel = (res, name, loadtype) => {
let blob = null
if (loadtype !== '' && loadtype === 'zip') { // zip
blob = new Blob([res], { type: 'application/zip' })
const objectURL = URL.createObjectURL(blob)
const downEle = document.createElement('a')
downEle.href = objectURL
downEle.setAttribute('download', `${name}.zip`)
document.body.appendChild(downEle)
downEle.click()
} else { // Excel
blob = new Blob([res], { type: 'application/vnd.ms-excel' })
const objectURL = URL.createObjectURL(blob)
const downEle = document.createElement('a')
downEle.href = objectURL
downEle.setAttribute('download', `${name}.xlsx`)
document.body.appendChild(downEle)
downEle.click()
// blob = new Blob([res], { type: 'application/vnd.ms-excel' })
// const url = window.URL.createObjectURL(blob)
// const link = document.createElement('a') // 创建a标签
// link.href = url
// link.download = name// 重命名文件
// document.body.appendChild(link)
// link.click()
// document.body.removeChild(link)
}
}