实例代码
<hz-table class="hz-table" :data="historyList" height="400">
<hz-table-column prop="createdTime" label="创建时间"></hz-table-column>
<hz-table-column prop="isStatic_dictText" label="汇总方式"></hz-table-column>
<hz-table-column label="操作" align="center" :width="1.4 | remToPx">
<template slot-scope="scope">
<hz-button type="text" @click="downloadHistoryExcel(scope)">下载</hz-button>
</template>
</hz-table-column>
</hz-table>
一.简单的文件下载可以使用window.open(url)方法(会新开一个窗口,如果是在钉钉可能会不太方便)
downloadPath: window.location.protocol + '//' + window.location.host + process.env.VUE_APP_BASE_API
1.window.open(url)方法
downloadHistoryExcel(scope){
console.log('汇总历史下载--', scope)
//下载文件
let url = this.downloadPath + '/sys/task/downloadStaticHis/' + scope.row.reportSeq + '/2?X-Access-Token=' + store.getters.token;
window.open(url);
},
2.使用隐藏的<a>标签在当页下载不会新开一个页面
downloadHistoryExcel(scope){
console.log('汇总历史下载--', scope)
//下载文件
let url = this.downloadPath + '/sys/task/downloadStaticHis/' + scope.row.reportSeq + '/2?X-Access-Token=' + store.getters.token;
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.download = '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
3.对于大文件建议使用fetch+blob的方式更可控,允许你监听整个下载过程,错误处理,完成下载给出提示
async downloadHistoryExcel(scope) {
const url = this.downloadPath + '/sys/operTask/getTask/' +
scope.row..taskId + '/2/' + scope.row.operNo + '/?X-Access-Token=' +
store.getters.token;
try {
// 发起请求获取文件内容
const response = await fetch(url, {
method: 'GET',
headers: {
// 如果需要额外的 header,可以在这里添加
'Content-Type': 'application/octet-stream'
}
});
if (!response.ok) {
throw new Error('网络请求失败,状态码:' + response.status);
}
// 将响应内容转换为 Blob
const blob = await response.blob();
// 创建临时 URL 并创建 a 标签进行下载
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = 'downloaded_file.ext'; // 可从响应头中动态获取文件名
// 添加到 body 并模拟点击
document.body.appendChild(link);
link.click();
// 清理
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
// 提示下载成功
this.$message.success('文件下载成功');
} catch (error) {
console.error('下载出错:', error);
this.$message.error('文件下载失败,请重试');
}
}
也欢迎大佬们指正,完善。江湖最高礼仪(抱拳)(抱拳)