在Vue中需要实现文件下载功能时,我们会根据后端返回的数据类型,来实现不同的下载方式
需求一:后端接口返回URL地址,要求不打开文件,直接实现PDF下载
实现方法:
<template>
<el-table :data="userList" stripe>
<el-table-column label="操作" width="210" >
<template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)">下载</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
methods: {
/** 下载 */
handleDownload (row) {
const data = {
contentId: row.id,
fileType: 5,
}
this.$confirm("是否确认下载这条数据项?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
}).then(() => {
return getSysFileInfo(data); //这是后端提供的下载接口
}).then(res => {
const fileName = res.data.oldFileName
const url = res.data.filePath; //返回的url下载地址 https://***.com/law-20240424111703-1713928623467.docx?e=1714011917&token=Ky3hFo-oWCjJvvvqVVeA2xIe2NeNITdw5m5rXgic:hP4lVWLoezPdOG54T76friE6MD8=
//调下载方法
this.downloadFile(url, fileName)
}).catch(() => { });
},
/** 根据接口返回的url实现下载 */
downloadFile (url, fileName) {
axios({
url,
method: 'GET',
responseType: 'blob', // 重要
}).then((response) => {
const blob = new Blob([response.data]);
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName; // 文件名
link.click();
}).catch((error) => {
console.error(error);
});
},
}
};