vue下载附件按钮功能
一.tools文件夹下tools文件中封装下载方法:
function iframeEle(imgsrc, fileName) {
let image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
image.onload = function () {
let canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
let context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
let a = document.createElement('a') // 生成一个a元素
let event = new MouseEvent('click') // 创建一个单击事件
a.download = fileName || 'photo' // 设置图片名称
a.href = url // 将生成的URL设置为a.href属性
a.dispatchEvent(event) // 触发a的单击事件
}
image.src = imgsrc
return Promise.resolve()
}
exports.download = (url, fileName, failCallbacck) => {
try {
iframeEle(url, fileName)
} catch (e) {
failCallbacck && failCallbacck(e)
}
}
二.导入方法:
三.使用方法:
handleDownload() {
// 员工表模板下载
let url = `${config.api_v1}company/staff/template/url?token=${this.$user.token}`;
download(url,"photo");
},