前端预览、下载二进制文件流(png、pdf)

前端请求设置 responseType: "blob"

后台接口返回的文件流如下:

拿到后端返回的文件流后:

预览

javascript 复制代码
<iframe  :src="previewUrl" frameborder="0" style="width: 500px; height: 500px;"></iframe>

1、预览

javascript 复制代码
view(data) {
     // 文件类型            
     let fileType = this.fileName.slice(this.fileName.length - 3).toUpperCase();
     let myBlob = '';
     //不同文件类型设置不同的type            
     if (fileType == 'PDF') {
          myBlob = new window.Blob([data], { type: 'application/pdf' });
     } else {
          myBlob = new window.Blob([data], { type: 'image/png' });
     }
     const previewUrl = window.URL.createObjectURL(myBlob);
     this.previewUrl = previewUrl;// iframe预览
    // window.open(previewUrl, '_blank');// 浏览器新打开窗口        
},

2、下载

javascript 复制代码
// 下载        
downFile() {
   var data = this.fileData;
   var fileType = this.fileName.slice(this.fileName.length - 3).toUpperCase();
   var blob = "";
   if (fileType == 'PDF') {
       blob = new window.Blob([data], { type: 'application/pdf' });
   } else if (fileType == 'PNG') {
       blob = new window.Blob([data], { type: 'image/png' });
   }
   const a = document.createElement("a");
   const objectUrl = URL.createObjectURL(blob);
   a.setAttribute("href", objectUrl);
   a.setAttribute("download", this.fileName);
   a.click();
   URL.revokeObjectURL(a.href); // 释放url        
}
相关推荐
wangruofeng12 分钟前
Phosphor Icons 官网源码拆解:URL 即存储、水波动画与 7362 Star 图标库的架构实践
前端·架构·github
BigTopOne31 分钟前
WebRTC Native / Android 开发学习资源整理
前端
excel1 小时前
nuxt 3 升级 nuxt 4 报错之 hasInjectionContext
前端
何以解忧,唯有..2 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
软件聚导航3 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
恋猫de小郭3 小时前
看懂大模型架构术语,帮助你理解目前常见的大模型开源架构
前端·人工智能·ai编程
yma163 小时前
通过提示词实现GitHub Pages 和 Nginx 双部署竟然这么简单?
前端
前端 贾公子3 小时前
第09章:上下文与记忆 (2)
java·服务器·前端
可乐鸡翅yeah_3 小时前
第三方接口对接 M3U8 流媒体排坑实战,解决外部服务商流兼容难题
前端·javascript·python·django·html·m3u8·m3u8在线
GoppViper4 小时前
RDF资源描述框架深度解析:语义Web的数据基石与实战逻辑
前端·数据库