vue下载文件和图片,窗口的打开关闭
根据图片路径下载到本地(解决图片跨域问题)
/**
* 根据图片路径下载图片
* @param imgsrc 图片地址
* @param name 保存的图片名
*/
downloadImage(imgSrc, name) {
var image = new Image();
// 解决跨域 Canvas 污染问题,
image.setAttribute("crossorigin", "anonymous");
image.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, image.width, image.height);
var url = canvas.toDataURL("image/png"); // 将图片格式转为base64
var a = document.createElement("a"); // 生成一个a元素
var event = new MouseEvent("click"); // 创建一个单击事件
a.download = name || "myPhoto"; // 设置图片名称
a.href = url; // 将生成的URL设置为a.href属性
a.dispatchEvent(event); // 触发a的单击事件
};
image.src = imgSrc + '?time=' + Date.now(); // 注意,这里是灵魂,否则依旧会产生跨域问题
}
下载文件
使用示例: download(url, “保存名字”);
备注:url 文件的下载地址
/**
* 下载
* @param {String} url 目标文件地址
* @param {String} filename 想要保存的文件名称
*/
download(url, filename) {
if (filename == null || filename.length == 0) {
if (url == null || url.length == 0) {
return;
}
window.open(url, "_blank").location;
} else {
const that = this;
this.getBlob(url, function (blob) {
that.saveAs(blob, filename);
});
}
},
/**
* 获取 blob
* @param {String} url 目标文件地址
* @return {cb}
*/
getBlob(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
},
/**
* 保存
* @param {Blob} blob
* @param {String} filename 想要保存的文件名称
*/
saveAs(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement("a");
const body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// fix Firefox
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
},
打开窗口
/**
* 打开新的网页
*/
openWithUrl(url) {
if (url == null || url.length == 0) {
return;
}
if (DeviceHelper.getBrowserType() == "Safari") {
const newPage = window.open("newPage", "_blank");
newPage.location = url;
} else {
window.open(url, "_blank").location;
}
},
关闭窗口
/**
* 关闭窗口
*/
closeWindowEvent() {
const { userAgent } = navigator;
if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
window.opener = null;
window.open("", "_self", "");
// window.open(" ", "_self").location;
window.location.href = "about:blank";
window.close();
} else {
window.opener = null;
window.open("", "_self", "");
// window.open(" ", "_self").location;
window.location.href = "about:blank";
window.close();
}
},