【学习记录20】vue使用blob流预览word ,Excel,pdf,TXT,图片,视频

这篇具有很好参考价值的文章主要介绍了【学习记录20】vue使用blob流预览word ,Excel,pdf,TXT,图片,视频。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

TXT,PDF直接使用浏览器本身预览

excel使用插件 xlsx,这个插件需要用到arraybuffer的流格式,我是使用前端转换的详见js代码,也可以叫后台返回arraybuffer的数据流

word 使用插件  docx-preview

话不多说直接上菜,css样式自己调就行

一、安装插件

  1. npm install xlsx --save

  2. npm install docx-preview --save

二、HTML部分

<el-dialog
    title="文件预览"
    :visible.sync="dialogVisible"
    fullscreen
    append-to-body
    :before-close="handleClose"
    class="file-dialog">
    <div style="width: 100%;height: 100%;">
      <img v-if="imgUrl" :src="imgUrl" alt="" style="width: 100%;height: 100%">
      <!-- pdf和txt使用iframe -->
      <iframe v-if="pdfUrl" :src="pdfUrl" frameborder="0" style="width: 100%;height: 100%;min-height: 500px;"></iframe>
      <video v-if="videoUrl" :src="videoUrl" controls style="width: 100%;height: 100%;max-height: 800px;"></video>
      <div v-if="docFile">
        <div ref="file"></div>
      </div>
      <div v-if="xlsFile" class="excel-view-container">
        <!-- Excel使用tab选项卡来模拟表格里的sheet业 -->
        <el-tabs type="border-card" v-if="sheetNames && sheetNames.length" @tab-click="handleClick">
          <el-tab-pane :label="item" v-for="(item, index) in sheetNames" :key="index">
            <div class="excelView" v-html="excelView"></div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </el-dialog>

三、js部分

<script>
  // 定义blob对应的type
  const fileTypeMap = {
    "xls": "application/vnd.ms-excel",
    "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "doc": "application/msword",
    "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "pdf": "application/pdf",
    "ppt": "application/pdf",
    "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    "png": "image/png",
    "gif": "image/gif",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "txt": "text/plain",
  }
  export default {
    data() {
      return {
        imgUrl: '', //图片路径
        pdfUrl: '', //pdf路径
        videoUrl: '', //视频路径
        excelView: '', //表格转换后的html数据
        docFile: false, //是否是word文件
        xlsFile: false, //是否是Excel文件
        execlArraybufferData: null, //Excelblob转换为arraybuff数据
        sheetNames: null, //从数据中获取到的sheet页数组
        imgType: ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng'],
      videoType: ['wmv', 'asf', 'asx', 'rm', 'rmvb', 'mp4', '3gp', 'mov', 'm4v', 'avi', 'dat', 'mkv', 'flv', 'vob'],
      wordType: ['text', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rar', 'zip', '7z', 'apz', 'ar', 'bz', 'car', 'dar', 'cpgz', 'f', 'ha', 'hbc', 'hbc2', 'hbe','hpk','hyp'],
      }
    },
    methods: {
      // 获取文件后缀
      getFileType(name) {
        if (name) {
          if (name.lastIndexOf(".") > -1) {
            return name.slice(name.lastIndexOf(".")+1);
          } else {
            return false
          }
        }
      },
      // 预览文件
      filePreviewPDF(path, name) {
        let fileType = this.getFileType(path), url, data
        // 后台接口方法url:接口地址,data给后台传的参数
        this.fileView(url, data).then(res => {
          let type = ''
          if (fileType) {
            type = fileTypeMap[fileType]
            if (this.imgType.includes(fileType)) {
              // 图片类型的
              const blob = new Blob([res], { type })
              this.imgUrl = window.URL.createObjectURL(blob)
            } else if (this.videoType.includes(fileType)) {
              // 视频类型的
              const blob = new Blob([res])
              this.videoUrl = window.URL.createObjectURL(blob)
            } else if (fileType === 'pdf' || fileType === 'txt') {
              // pdf和文本类型的,用iframe打开
              const blob = new Blob([res], { type })
              this.pdfUrl = window.URL.createObjectURL(blob)
            } else if (fileType === 'doc' || fileType === 'docx') {
              // word类型的用docx-preview插件
              this.docFile = true
              let docx = require("docx-preview")
              this.$nextTick(() => {
                docx.renderAsync(res, this.$refs.file).then(x => console.log("docx: finished",x))
              })
            } else if (fileType === 'xls' || fileType === 'xlsx') {
              // 表格类型的用xlsx插件
              this.xlsFile = true
              let XLSX = require("xlsx")
              this.XLSX = XLSX
              this.execlType = type
              let blob = new Blob([res], {type: this.execlType})
              let reader = new FileReader()
              reader.readAsArrayBuffer(blob) // blob类型转换为ArrayBuffer类型
              this.tabChange(0, reader)
            } else {
              this.handleClose()
              this.$modal.msgError('不支持此文件预览')
            }
          } else {
            this.handleClose()
            this.$modal.msgError('不支持此文件预览')
          }
        })
      },
      handleClick(data) {
        this.tabChange(data.index)
      },
      tabChange(index, reader) {
        this.excelView = ''
        let XLSX = this.XLSX
        let _this = this

        // 如果第一次进来
        if (!this.sheetNames) {
          // 文件转换加载完成后
          reader.onload = function() {
            let arraybufferData = this.result
            this.execlArraybufferData = arraybufferData
            let data = new Uint8Array(arraybufferData) // es2017的方法
            let workbook = XLSX.read(data, { type: "array" })  // 得到表格的array数据
            _this.workbooks = workbook  // 赋值到此组件最外面,一会要用
            let sheetNames = workbook.SheetNames; // 得到execl工作表名称集合,结果类似这样['sheet1','sheet2']
            _this.sheetNames = sheetNames  // 赋值到此组件最外面,一会要用
            let worksheet = workbook.Sheets[sheetNames[index]]  // 获取第几个工作表0就是'sheet1',以此类推
            _this['excelView'] = XLSX.utils.sheet_to_html(worksheet) // 把表格的array数据转换成html数据
            _this.$nextTick(function () {
              // DOM加载完毕后执行,解决HTMLConnection有内容但是length为0问题。
              _this.setStyle4ExcelHtml();
            })
          }
        } else {
          // 已经有数据了的时候直接获取对应sheet里的内容
          let worksheet = this.workbooks.Sheets[this.sheetNames[index]];
          this['excelView'] = XLSX.utils.sheet_to_html(worksheet)
        }


      },
      // 设置Excel转成HTML后的样式
      setStyle4ExcelHtml() {
        const excelViewDOM = document.getElementById("excelView");
        if (excelViewDOM) {
          const excelViewTDNodes = excelViewDOM.getElementsByTagName("td"); // 获取的是HTMLConnection
          if (excelViewTDNodes) {
            const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes);
            for (const i in excelViewTDArr) {
              const id = excelViewTDArr[i].id; // 默认生成的id格式为sjs-A1、sjs-A2......
              if (id) {
                const idNum = id.replace(/[^0-9]/gi, ""); // 提取id中的数字,即行号
                if (idNum && (idNum === "1" || idNum === 1)) {
                  // 第一行标题行
                  excelViewTDArr[i].classList.add("class4Title");
                }
                if (idNum && (idNum === "2" || idNum === 2)) {
                  // 第二行表头行
                  excelViewTDArr[i].classList.add("class4TableTh");
                }
              }
            }
          }
        }
      },
      handleClose() {
        this.$emit('closeDialog', false)
      }
    }
  }
</script>

思路来源于以下链接;

vue 在线预览 word ,Excel,pdf,图片 数据流 内网文件流 亲测有效_勤能补拙(vue小白一枚)的博客-CSDN博客_vue word预览

vue中页面预览后端传来的excel流文件_Famiglistimo-run的博客-CSDN博客_vue 预览excel文件流文章来源地址https://www.toymoban.com/news/detail-641161.html

到了这里,关于【学习记录20】vue使用blob流预览word ,Excel,pdf,TXT,图片,视频的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Vue实用功能】Vue实现文档在线预览功能,在线预览PDF、Word、Excel、ppt等office文件

    Luckysheet 是一个类似于 excel 的在线电子表格,功能强大、配置简单且完全开源。 安装 Luckysheet 1、通过CDN引入依赖 由于 Luckysheet 现在还没有发布出模块化的开发,不能使用 npm,所以我们需要在 VUE 项目中手动引入相关文件。编辑 public/index.html 文件,在里面添加如下代码 2、指

    2023年04月22日
    浏览(43)
  • Vue3 实现文件预览 Word Excel pdf 图片 视频等格式 大全!!!!

    先上效果图    插件安装 先说 word 文件是docx-preview插件           excel文件是用 xlsx 插件     介绍后端返回的数据 因为在拦截器处 做了对数据的处理 最后你调接口拿到的数据是 一个对象 里面包含: url :  blob对象转换的用于访问 Blob 数据的临时链接。这个链接可以被用于

    2024年02月07日
    浏览(51)
  • 前端(vue)js在线预览PDF、Word、Excel、ppt等office文件

    可选参数 pdf=true,word文档尝试以pdf方式显示,默认false watermark=水印文本,显示文本水印;“img:”+图片url表示图片水印,如:img:https://view.xdocin.com/demo/wm.png saveable=true,是否允许保存源文件,默认false printable=false,是否允许打印,默认true ©able=false,是否允许选择复制内容,

    2024年02月13日
    浏览(54)
  • element ui vue 附件预览组件、可预览图片、excel 、pdf.word等文件(浏览器打开文件的方式)

    目录 1.组件源码  2.html 代码 3.组件源码  此组件就是一个单纯的预览图片、浏览器打开文件的形式简单的组合了下而成的,word、excel是直接下载、pdf浏览器打开的形式,如果想本地打开直接预览的话就直接不用看了。word、excel、pdf 的图片是我放到服务器上的图片地址。 1.组

    2024年02月11日
    浏览(48)
  • uniApp 使用uni.openDocument(object)预览pdf、excel、word等文件

    这里咱们直接用的uniapp官方提供的uni.downloadFile方法调用手机第三方能打开文件的工具,比如wps等(ps:这里实现的是APP文件预览)。 1.文件路径(url)必须是浏览器能直接访问的文件。比如:http://xx.cc.com/images/abc.xlsx 这种格式。 最开始我是用的后台给的接口 file/dowload?fileId=1

    2024年02月11日
    浏览(46)
  • 前端实现文件预览(pdf、excel、word、图片)

    需求:实现一个在线预览pdf、excel、word、图片等文件的功能。 介绍:支持pdf、xlsx、docx、jpg、png、jpeg。 以下使用Vue3代码实现所有功能,建议以下的预览文件标签可以在外层包裹一层弹窗。 sandbox 这个属性如果是单纯预览图片可以不使用,该属性对呈现在 iframe 框架中的内容

    2024年02月10日
    浏览(48)
  • Java POI导出Word、Excel、Pdf文档(可在线预览PDF)

    1、导入依赖Pom.xml        dependency             groupIdorg.apache.poi/groupId             artifactIdpoi/artifactId             version3.14/version         /dependency 2、Controller   3、Service a、pdfService b、wordService c、excelService  4、Utils 5、模板截图   6、前端

    2024年02月08日
    浏览(37)
  • ios 实现PDF,Word,Excel等文档类型的读取与预览

    最近正在研发的项目有一个需求: 允许用户将iCloud中的文档上传,实现文件的流转。 以前接触的项目对于资料类的上传大多是仅限于图片与视频。对于文档类(PDF, Word, Excel, Text等), 因苹果的沙箱环境限制,想要读取文件是无法实现的。目前虽然可以支持选择文件,但只能通

    2024年02月06日
    浏览(34)
  • 文档在线预览(四)将word、txt、ppt、excel、图片转成pdf来实现在线预览

    @ 目录 事前准备 1、需要的maven依赖 添加spire依赖(商用,有免费版,但是存在页数和字数限制,不采用spire方式可不添加) 2、后面用到的工具类代码: 一、word文件转pdf文件(支持doc、docx) 1、使用aspose方式 2、使用poi方式 3、使用spire方式 二、txt文件转pdf文件 三、PPT文件转

    2024年02月08日
    浏览(76)
  • Vue预览word/pdf文件(内外网均可)

    预览word文件实现方式有  1 将文件放在前端静态文件中 实现本地预览 但前端包变得很大 多文件不适合 2 通过跳转外网链接访问 但内网无法使用 3 综合考虑 利用浏览器自带的预览pdf  将文件放在服务器指定目录下 前端代码量很少 无需任何插件 只需调用后端接口(将文件转

    2024年02月11日
    浏览(67)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包