本文章在于记录一下在项目中遇到的一些问题,笔者多用于记录,毕竟好记性不如烂笔头!!!
重点:responseType:"blob",确保接收到的文件不是乱码
各类文件流类型合集:Vue 之 new Blob() 文件流下载文件不同文件类型的 type 值整理_敬威的博客-CSDN博客
// 接口
export function downloadZip(params) {
return request({
methods: "get",
url: "/api/download",
params: params,
responseType: "blob",
});
}
// 使用页面
<template>
<div>
<el-button @click="downloadZip">下载zip</el-button>
</div>
</template>
<script>
import { downloadZip } from "@/api/download"
export default {
methods: {
download() {
downloadZip().then(res => {
let blob = new Blob([res], {
type: 'application/zip',
});
let link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
//重命名文件
link.download = "证书附件.zip";
link.click();
//释放内存
window.URL.revokeObjectURL(link.href);
})
}
}
}
</script>
<style></style>