前言
首先,咱们先开始了解一下什么是文件流,是以外存文件为输入输出对象的数据流。每一个文件流都有对应的内存缓冲区与之对应。文件流不是由若干个文件组成的流,流是数据传输的过程,文件流指的是以文件为输入输出对象的流,简而言之 ,在前后端数据传递之中,采用一种像水流一样的方式进行文件或图片的下载或预览。
二进制流在项目中的运用
- 二进制流的腿片预览
- 二进制流的PDF预览
- 二进制流文件下载
- 流文件和base64字符串互传
二进制流预览处理
对于二进制流产生的文件或者图片的预览,常见就是我们在pc上生成一份二维码的图片需要进行扫码,或者是需要对相关材料生成的文件进行案件预览,那我们在项目中应该怎么处理呢 ?话不多说上代码
1、二进制流图片的预览(两种方式)
//前端页面展示使用img标签的src 作为图片展示的方法
<template>
<div>
<img class="img-code" :src="qrcode" />
</div>
</template>
export default {
data() {
return {
qrcode: '',,
}
},
created() {
},
async mounted() {
this.getconfirmQrCode()
},
methods: {
//方式一:blob处理后端返回的数据
getconfirmQrCode() {
confirmQrCode({
后端接口的参数 })
.then((res) => {
const myBlob = new window.Blob([res], {
type: 'image/png' })
const qrUrl = window.URL.createObjectURL(myBlob)
this.qrcode = qrUrl
})
},
//方式二:axios指定responseType为blob类型接收响应:
getconfirmQrCode() {
confirmQrCode({
后端接口的参数, responseType: 'blob', })
.then((res) => {
this.qrcode = window.URL.createObjectURL(res);
})
},
},
}
1、二进制流PDF的预览(两种方式)
//前端页面展示使用iframe标签的src 作为图片展示的方法
<template>
<div>
<iframe :src="src" frameborder="0" style="width: 100%; height: 500px"></iframe>
</div>
</template>
二进制流的下载处理
后端返回的数据如上图,我们只需要调整一下如下内容
function handleDownloadFile(uuid, fileName) {
const file = await downloadFile(uuid); // 下载接口,返回文件流
const blob = new Blob([file]);
const a = document.createElement("a");
const objectUrl = URL.createObjectURL(blob);
a.setAttribute("href", objectUrl);
a.setAttribute("download", fileName);
a.click();
URL.revokeObjectURL(a.href); // 释放url
}
以上就是文件流处理的相关内容啦,如果觉得不错的话,别忘了点赞关注,评论区留下宝贵的小心心哦~