在js实现文件下载的时候,当下载图片或者文本的时候,浏览器往往是打开该文件,而不是下载该文件,尽管设置了a标签的download属性,也达不到想要的效果,看了fileSaver的方法后采取了相同的方法,记录一下。
通过XMLHttpRequest请求将下载地址数据转换成blob格式,然后再通过a标签进行下载。代码如下:
// url文件地址,name文件名称
getBlobData(url, name) {
var self = this
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = function () {
self.saveAs(xhr.response, name);
};
xhr.onerror = function () {
console.error('could not download file');
};
xhr.send();
}
saveAs(data, name) {
const blob = new Blob([data], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = name; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href);
}