下载基础代码直接Copy
/**文件下载代码
* @param {Object} res
* @param {Object} Name 文件名称
*/
hrefClick(res, Name) {
const content = res
const blob = new Blob([content])
const fileName = Name
if ('download' in document.createElement('a')) { // 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else { // IE10+下载
navigator.msSaveBlob(blob, Name)
}
/* this.$message.success("导出成功")*/
},
//获取图片的Blob值
getImageBlob(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
console.log();
if (cb) cb(this.response);
}
};
xhr.send();
},
使用
/**
*
* @param {Object} url 下载地址 比如 xxx.jpg
*/
toOpen: function(url) {
var _this = this;
// this.$store.state.home.oss + '/' + url = https://www.baidu.com/xxx.jpg (文件全路径)
this.getImageBlob(this.$store.state.home.oss + '/' + url, function(blob) {
_this.hrefClick(blob, url.substring(url.lastIndexOf('/') + 1, url.length))
});
},