页面效果:
html
<a v-if="isPicture(record.extension)" href="javascript:;"@click="dowload(urls + record.filePath, record.name, 1)"><a-icon type="download" />
<span class="icon-addmargin">下载</span></a>
<a v-else @click="dowload(urls + record.filePath, record.name, 2)">
<a-icon type="download" /><span class="icon-addmargin">下载</span></a>
js
// vue文件下载js
dowload(imgsrc, name, type) {
if (type == 1) {
if (!imgsrc) {
return;
}
downImage(imgsrc, name);
} else {
downloadFile(imgsrc, name);
}
},
//引入js文件代码
// 文件下载ppt,xls,word
export function downloadFile(str, fileName) {
let that = this;
getBlob(str, function (blob) {
saveAs(blob, fileName);
});
function getBlob(url, cb) {
console.log("调用getBlob");
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
}
function saveAs(blob, filename) {
console.log("调用saveAs");
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
var body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
}
// url下载文件图片
export function downImage(src, name) {
getUrlBase64(src).then((base64) => {
let a = document.createElement("a");
a.style.display = "none";
a.download = name;
a.href = base64;
document.body.appendChild(a);
a.click();
});
}
function getUrlBase64(url) {
return new Promise((resolve) => {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image();
img.crossOrigin = "Anonymous"; //允许跨域
img.src = url;
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0, img.width, img.height);
let dataURL = canvas.toDataURL("image/png");
canvas = null;
resolve(dataURL);
};
});
}
总结:代码网上都有很多人分享代码,从网上拉取代码的关键不在于复制别人的代码,解决自己的问题。今天看了文章最上面推荐的文章,看到了方法一另一个方法为参数的使用方式,我觉得真的是见识到了代码的精妙,看好的代码是学习和享受的过程!