下载Blob流
文件,并以服务形式显示文件下载进度
1、下载接口 增加 config
参数,并用...config
将该属性加入到请求中;
xxapi.js
文件中设置downloadFile
下载接口
// 下载文件
export function downloadFile(data, config) {
return request({
url: '/xx/downloadFile',
method: 'post',
data: data,
responseType: 'blob',
timeout: 120 * 60 * 1000,
...config
})
}
2、在页面中添加以下代码
<el-button type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
<script>
import { downloadFile } from "@/api/xxapi";
import { Loading } from 'element-ui'
let downloadLoadingInstance;
export default {
name: "DownloadFile",
data() {
return {
downloadProgress: 0
}
},
methods: {
handleDownload(row) {
var that = this;
downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候 " + that.downloadProgress + '%', spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
const config = {
onDownloadProgress: progressEvent => {
if (progressEvent.lengthComputable) {
that.downloadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
downloadLoadingInstance.text = "正在下载数据,请稍候 " + that.downloadProgress + '%';
}
}
};
// 从后端请求到 二进制数据,并由后端转成blob
downloadFile({ url: row.url }, config).then((response) => {
let downloadName = `${row.fileName}`;
this.downloadBlob(response, downloadName); // 二进制流直接取response
downloadLoadingInstance.close(); // 关闭加载loading效果
});
},
// 下载文件流格式的文件
downloadBlob(response, downloadName) {
let blob = new Blob([response], {
type: "application/json;charset=utf-8",
});
let href = window.URL.createObjectURL(blob); // 创建下载的链接
if (window.navigator.msSaveBlob) {
try {
window.navigator.msSaveBlob(blob, downloadName);
} catch (e) {
console.log(e);
}
} else {
// 谷歌浏览器 创建a标签 添加download属性下载
let downloadElement = document.createElement("a");
downloadElement.href = href;
downloadElement.target = "_blank";
downloadElement.download = downloadName; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
}
}
}
}
</script>