小工具知识网

当前位置: 首页 > 行业知识 > vue项目,后端返回二进制文件流,前端如何实现文件在线预览

行业知识

vue项目,后端返回二进制文件流,前端如何实现文件在线预览

2026-11-14 10:36:34 来源:互联网转载
  预览

点击按钮,弹个框,框里是文件的容器元素。然后用v-if来控制元素的隐藏与显示以下是结构。

                                               

前端要用到的插件:

execl用到的是import XLSX from 'xlsx'; 可以用npm  i xlsx下载,支持xls,xlsx。

word用到的是 const docx = require("docx-preview"); window.JSZip = require("jszip");

可以用npm i docx-preview@0.1.4 (版本可以根据自己的情况,我是直接用的这个) , npm i jszip下载,支持doc,docx。

import XLSX from 'xlsx';//引入const docx = require("docx-preview");window.JSZip = require("jszip");

在methods定义函数,用axios调后端接口,拿到后端返回的数据,根据文件格式进行对应的处理

  // 文件预览    openPdfViewer(scope) {      // return      // this.fileId = scope.row.id;      var formdata = new FormData();      formdata.append('id', scope.row.id);      if (scope.row.attachmentName.endsWith('.pdf')) {        this.$axios({          url: '/businessTechnology/preview',          data: formdata,          method: 'post',          responseType: 'blob'        }).then(res => {          // console.log(res.data.type);          this.previewDialog = true          this.previewType = 1          const blob = new Blob([res.data], { type: 'application/pdf' });          // 创建用于作为PDF预览源的Blob的URL          this.url = URL.createObjectURL(blob);        }).catch(error => {          console.error('Error getting file:', error);        });      } else if (scope.row.attachmentName.endsWith('.xls') || scope.row.attachmentName.endsWith('.xlsx')) {        console.log('execl');        this.$axios({          method: 'post',          data: formdata,          responseType: 'arraybuffer', // 设置响应体类型为arraybuffer          url: '/businessTechnology/preview',        }).then(res => {          console.log(res);          this.previewDialog = true          this.previewType = 2          let workbook = XLSX.read(new Uint8Array(res.data), { type: "array" }); // 解析数据          let worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表          this.excelHtml = XLSX.utils.sheet_to_html(worksheet); // 渲染          console.log(this.excelHtml);        });      } else if (scope.row.attachmentName.endsWith('.doc') || scope.row.attachmentName.endsWith('.docx')) {        console.log('word');        this.$axios({          method: 'post',          data: formdata,          responseType: 'blob',          url: '/businessTechnology/preview',        }).then(res => {          this.previewType = 3          this.previewDialog = true          this.$nextTick(()=>{            docx.renderAsync(res.data,this.$refs.word) // 渲染到页面预览          })          });      }    },

本人亲测,可以正常使用,有问题可以一起探讨。

上一篇:怎么买服务器机柜?

下一篇:B站视频下载至本地存储的详细指南