一、接口返回的数据流格式
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210521145642679.png)
二. 方法实现
1. image 图片类型
<img :src="imageUrl" alt="" srcset="" />
async getData() {
const res = await axios.post(
"/project/download",
{
id: "",
},
{
responseType: "blob",
transformResponse: [
async (data) => {
return await this.transformData(data);
},
],
}
);
let blob = new Blob([res.data], { type: "image/jpeg" });
this.imageUrl = URL.createObjectURL(blob);
},
2. txt 文件类型
<div>{{ txtContent }}</div>
async getData() {
const res = await axios.post(
"/project/download",
{
id: "",
},
{
responseType: "blob",
transformResponse: [
async (data) => {
return await this.transformData(data);
},
],
}
);
res.data.then((data) => {
this.txtContent = data;
});
},
transformData(data) {
return new Promise((resolve) => {
let reader = new FileReader();
reader.readAsText(data, "UTF-8");
reader.onload = () => {
resolve(reader.result);
};
});
},
3. pdf 文件类型
<iframe
:src="pdfUrl"
frameborder="0"
style="background-color: white"
allowTransparency="true"
height="100%"
width="100%"
></iframe>
async getData() {
const res = await axios.post(
"/project/download",
{
id: "",
},
{
responseType: "blob",
headers: {
"Content-Type": "application/pdf;charset=UTF-8",
},
}
);
let blob = new Blob([res.data], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
this.pdfUrl = url;
},