需求描述: 根据后端返回的url实现下载功能
/** download All*/
const downMethod = data => {
axios({
method: data.method,
url: apiUrl + data.url,
params: data.params,
responseType: "blob"
}).then(res => {
let timestamp = new Date().getTime();
const link = document.createElement("a");
let blob = new Blob([res.data], {
type: getFileType(data.params.fileType)
});
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download = data.fileName + moment(timestamp).format("YYYY-MM-DD"); //下载的文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Message({
// type: "success",
// message: "下载成功",
// center: true
// });
});
};
<div style="margin-top:22px;margin-bottom:22px;" v-if="basicInfos.produceAppendix.length>0">
<div class="download" v-for="(item,index) in basicInfos.produceAppendix" :key="index">
<span>{{item.appendixName}}</span>
<span style="cursor:pointer;color:#169BD5;padding-left:15px;" @click="download(item)">下载</span>
</div>
</div>
<div v-else style="margin-left:20px;margin-bottom: 16px;">暂无附件</div>
</div>
关键操作:调用utils.js里面的方法,处理文件名称。
//method里面的方法
// 下载
download(item) {
utils.downMethod({
method: "get",
url: "/download",
fileName: item.appendixName.split(".")[0], //截取文件名
params: {
fileType: item.appendixName.split(".")[1], //截取文件名后缀
filePath: item.appendixAddress
}
});
},