实现文件的下载功能
直接下载仅适用于浏览器无法识别的文件。
如果是浏览器支持的文件格式,如html、jpg、png、pdf等,则不会触发文件下载,而是直接被浏览器解析并展示
下载压缩包,默认a连接下载图片,默认a连接
对于一些浏览器无法识别的文件格式,可以直接再浏览器地址栏输入url即可触发浏览器的下载功能。
浏览器可以识别的会自动打开预览界面
window.location.href ='xxxxx.rar'window.open('http://resource.teld.cc/teldimage/142/c7c5db8e52e748b8affe35625dbdc8ee.jpg')
function downloadFile(url, fileName) {var x = new XMLHttpRequest();x.open("GET", url, true);x.responseType = 'blob';x.onload = function (e) {console.log('x.response', x.response)var url = window.URL.createObjectURL(x.response)var a = document.createElement('a');a.href = url;a.download = fileName;a.click();}x.send();}
第二层axios 返回的就是
Blob 格式的数据类型所以可以不用再 new Blob ,直接用window.URL.createObjectURL(res.data) 就可以

# 别人的版本
function downloadFile(data,fileName){// data为blob格式var blob = new Blob([data]);var downloadElement = document.createElement('a');var href = window.URL.createObjectURL(blob);downloadElement.href = href;downloadElement.download = fileName;document.body.appendChild(downloadElement);downloadElement.click();document.body.removeChild(downloadElement);window.URL.revokeObjectURL(href); // 释放URL对象
}
1、掘金前端实现文件下载(含多文件下载思路)的几种方法
2、Blob MDN