vue 实现文件预览(支持pdf,xls、xlsx,doc、docx,jpg、jepg、png)

文章展示了如何在Vue项目中使用avue-crud组件进行数据展示,并结合vue-office插件实现PDF和Word文档的预览。针对Excel预览存在的问题,文章提到了需要取数组对象索引最长的作为显示内容,以解决显示不全的问题。此外,还提供了图片预览的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<avue-crud ref="crud" :option="fileOption" :data="dataCRUD" :page.sync="page" :search.sync="search" @current-change="currentChange" @size-change="sizeChange"
 @search-reset="searchReset" @search-change="searchChange">
      <!-- 预览 -->
       <template slot-scope="scope" slot="name">
            <el-link type="primary" @click="preview(scope.row)" :underline="false">{{scope.row.name}}</el-link>
       </template>                   
 </avue-crud>

预览的部分展示在dialog中,根据点击的文件类型进行判断展示

 export default {
        data() {
            return {
                excelURL: "", //文件地址,看你对应怎末获取、赋值
                fileType:'',//文件类型区分预览
                currentManages:[],//编辑时接口数据
                dialog: {
                    dialogVisible: false,
                    src: '',
                    isPdf: false,
                    isExcel: false,
                    isWord: false,
                    isPicture:false
                },
                maxExcelData:[],
                maxIndex:'',
            };
        },

其中pdf和docx文件使用的插件详情:https://github.com/501351981/vue-office

<!-- 预览 -->
  <el-dialog  :title="previewTitle" :visible.sync="dialog.dialogVisible"> 
              <div v-if="dialog.isPdf"> 
                    <vue-office-pdf 
                    :src="previewUrl"
                    @rendered="renderedHandler"
                    @error="errorHandler"
                />
                </div>
                <div  v-else-if="dialog.isWord">
                    <vue-office-docx
                    :src="previewUrl"
                    style="height: 100vh;"
                    @rendered="renderedHandler"
                    @error="errorHandler"
                />
                </div>
                <div v-else-if="dialog.isExcel"> 
                    <div id="table" >
                     <el-table :data="excelData" border  stripe 
:header-cell-style="{'background':'#F5F4F7'}">
                     <el-table-column
                      type="index"
                      label="序号"
                      width="60"
                      :resizable="false"
                      align="center" />
                     <el-table-column
                       v-for="(value, key, index) in excelData[maxIndex]"
                       :key="index"
                       :prop="key"
                       :label="key"></el-table-column>
                      </el-table>
                 </div>
                </div>
                <div  v-else-if="dialog.isPicture"> 
                    <div v-viewer>
                        <img  :src="previewUrl" :toolbar="false" width="900px"/> 
                      </div>
                </div>
        </el-dialog>

后面发现Excel 中sheet不能显示正确,所以找了另一个预览Excel插件,详见:vue在线预览word、excel、pdf、txt、图片的方法实例_vue.js_脚本之家

其中Excel在展示的时候会显示不全,需要取数组对象索引的长度最长的作为赋值对象

 // 预览
            preview(row){
                if (!(row.url.includes('.png') || row.url.includes('.jpg') || row.url.includes('.jpeg')  || row.url.includes('.JPG') || row.url.includes('.PNG') || row.url.includes('.JPEG')  || row.url.includes('.pdf') || row.url.includes('.xlsx') || row.url.includes('.xls') || row.url.includes('.doc'))) {
                    this.$message.error('文件类型不支持预览')
                    return false
                }
                if (row.url.includes('.pdf')) {
                    this.dialog.isPdf = true
                    this.dialog.isExcel = false
                    this.dialog.isWord = false
                    this.dialog.isPicture = false
                    this.dialog.src = ''
                    this.iframeLoading = true
                    this.previewTitle = row.name
                    // this.previewUrl = this.pdf
                    this.previewUrl = row.url
                } else if (row.url.includes('.xls')){
                    this.dialog.isPdf = false
                    this.dialog.isExcel = true
                    this.dialog.isWord = false
                    this.dialog.isPicture = false
                    this.previewTitle = '预览'
                    // row.url=this.xlsx
                    this.readWorkbookFromRemoteFile(row.url)
                }else if (row.url.includes('.doc')||row.url.includes('.docx')){
                    this.dialog.isPdf = false
                    this.dialog.isExcel = false
                    this.dialog.isWord = true
                    this.dialog.isPicture = false
                    this.previewTitle = row.name
                    // this.previewUrl = this.docx
                    this.previewUrl = row.url
                }else if (row.url.includes('.jpg')||row.url.includes('.JPG')||row.url.includes('.jpeg')||row.url.includes('.png')){
                    this.dialog.isPdf = false
                    this.dialog.isExcel = false
                    this.dialog.isWord = false
                    this.dialog.isPicture = true
                    this.previewTitle = row.name
                    this.previewUrl = row.url
                }
                this.dialog.dialogVisible = true
            },
 readWorkbookFromRemoteFile (url) {
                var xhr = new XMLHttpRequest();
                xhr.open("get", url, true);
                xhr.responseType = "arraybuffer";
                let _this = this;
                xhr.onload = function (e) {
                    if (xhr.status === 200) {
                    var data = new Uint8Array(xhr.response);
                    var workbook = XLSX.read(data, { type: "array" });
                    console.log("workbook", workbook);
            
                    var sheetNames = workbook.SheetNames; // 工作表名称集合
                    _this.workbook = workbook;
                    _this.getTable(sheetNames[0]);
                    }
                };
                xhr.send();
            },
  getTable(sheetName) {
                    console.log(sheetName);
                    var worksheet = this.workbook.Sheets[sheetName];
                    this.excelData = XLSX.utils.sheet_to_json(worksheet);
                    //取数组对象中,对象的key最长的一个进行赋值操作
                    let arr = []
                    let obj ={}
                    arr.push(obj)
                    let mapObj =  new Map()
                    let size = 0
                    for(let i= 0;i<this.excelData.length;i++){
                        let arrLength = 0
                        for(let key in this.excelData[i] ){
                            arrLength++
                        }
                        mapObj.set(i,arrLength)
                    //    console.log(mapObj)
                    }
                    let contrastNum = 0
                    this.maxIndex = 0
                    mapObj.forEach((value, key, self) => {
                            // console.log(key,'=>', value)
                            if(value>contrastNum){
                                contrastNum = value
                                this.maxIndex = key
                            }
                          
                    });
                    console.log(this.maxIndex,contrastNum,'999')
                   
        },

图片预览,详见:https://www.cnblogs.com/sgs123/p/12197278.html

Vue.js应用中预览`.doc`文件通常涉及到文件上传、处理以及显示内容的部分。你可以使用一些第三方库,如`vue-docx`或`vue-file-preview`,来实现这个功能。以下是基本步骤: 1. 安装依赖:首先需要安装处理`.doc`文件的库。对于`vue-docx`,可以使用npm或yarn: ``` npm install vue-docx ``` 2. 使用组件:引入并使用支持`.doc`文件预览的组件。例如,`vue-docx`提供了一个`VueDocxEditor`组件: ```html <template> <div> <VueDocxEditor :value="docContent" @change="handleDocumentChange"></VueDocxEditor> <button @click="previewDocument">预览</button> </div> </template> <script> import VueDocxEditor from 'vue-docx-editor'; export default { components: { VueDocxEditor }, data() { return { docContent: '', }; }, methods: { handleDocumentChange(newContent) { this.docContent = newContent; }, previewDocument() { // 实现文档预览逻辑,这里通常是生成一个临时的HTML文件供用户查看 let blob = new Blob([this.docContent], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); const url = URL.createObjectURL(blob); window.open(url, '_blank'); }, }, }; </script> ``` 3. 预览逻辑:当点击预览按钮时,你需要将`.doc`内容转换成可以在线预览的形式,比如创建一个临时的HTML文件。 请注意,直接在浏览器内解析`.doc`文件可能会受限于安全策略,所以这种方法并不总是可行,尤其是对于复杂的Word文档。如果需要更完整的编辑和预览体验,考虑使用专门的富文本编辑器,如TinyMCE等。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值