前端实现下载功能是依赖于浏览器特性,而非JS特性
前端如何实现文件下载,防止浏览器自动打开可预览文件
https://blog.csdn.net/weixin_46074961/article/details/105677732


1.location.href
下载文件–window-location-href

对于浏览器不能打开的文件(例如:.rar .doc等)是可以实现文件下载的,但是对于浏览器可以打开的(例如:.txt .xml等)只可以实现预览功能

window.location.href="https://106.14.15.103:8000/downloadFile/test"

2.window.open()

Window 接口的 open() 方法,是用指定的名称将指定的资源加载到浏览器上下文(窗口 window ,内嵌框架 iframe 或者标签 tab )。如果没有指定名称,则一个新的窗口会被打开并且指定的资源会被加载进这个窗口的浏览器上下文中。

//后台传来的下载路径url:https://106.14.15.103:8000/downloadFile/test//前端核心代码window.open(url);

很明显这个方法只能将指定路径的资源加载到浏览器里,如果该文件不能被浏览器预览,浏览器就会下载该文件,但是,如果浏览器可以预览该文件呢?是不是这个方法不可以实现?要求下载一个txt文本,用该方法浏览器会直接预览该txt文件。

3.a标签(可以直接下载)

a标签的href属性指定下载文件的路径,需要给a标签添加一个download属性,download指定下载文件保存时的名称。

<a href="https://106.14.15.103:8000/downloadFile/test" download="test.txt">下载</a>

上述三种都是通过加载文件url直接下载,如果后端返回文件流,则需要先转化为url再下载;
另外上述三种方式默认是get方式,如果需要使用post方式且需传参,最好使用第四种方式;


4.文件流下载

1.ajax请求将文件流下载下来2.将下载的文件流转化为blob数据3.通过 window.URL.createObjectURL(blob)将blob转化为url4.通过动态生成a标签 模拟点击事件下载
this.$http({ url: this.$http.adornUrl(`/strUrl/${id}`), method: 'get', responseType: 'blob', timeout: 1000 * 600 }).then(res => { console.log('res', res) if (res.status === 200) { const blob = new Blob([res.data], { type: `application/octet-stream` }) const downloadElement = document.createElement('a') const href = window.URL.createObjectURL(blob) downloadElement.href = href downloadElement.download = `${filename}` downloadElement.click() } else { this.$message.error('下载出错!') } })

5.iframe

<el-buttonsize="mini" @click="handleExport(scope.row)">导出</el-button>//method方法:handleExport(row) {var elemIF = document.createElement('iframe')elemIF.src = 'user/downloadExcel?snapshotTime=' + formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm') +'&category=' + row.category elemIF.style.display = 'none'document.body.appendChild(elemIF)}