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

<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

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Vue预览docxdocpdfxlsxlsx文件,可以使用第三方库来实现。 对于docxdocxlsxlsx文件,可以使用`js-xlsx`库来进行解析和预览。该库可以将Excel文件转换为JSON格式,而对于Word文件,可以使用`docx.js`库来进行解析和预览。 对于pdf文件,可以使用`pdf.js`库来进行预览。该库可以通过Canvas将PDF文件渲染成图片,然后在Vue中显示。 下面是一个示例代码,演示如何使用上述库来预览不同类型的文件: ```html <template> <div> <div v-if="fileType === 'docx' || fileType === 'doc'"> <div v-html="docContent"></div> </div> <div v-else-if="fileType === 'xls' || fileType === 'xlsx'"> <table> <tr v-for="row in excelData"> <td v-for="cell in row">{{ cell }}</td> </tr> </table> </div> <div v-else-if="fileType === 'pdf'"> <canvas ref="pdfCanvas"></canvas> </div> </div> </template> <script> import XLSX from 'xlsx'; import Docx from 'docx'; import pdfjsLib from 'pdfjs-dist'; export default { data() { return { fileType: '', docContent: '', excelData: [], }; }, mounted() { // 根据文件类型进行解析和预览 if (this.fileType === 'docx' || this.fileType === 'doc') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const doc = new Docx(); doc.load(content); this.docContent = doc.getHtml(); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'xls' || this.fileType === 'xlsx') { const reader = new FileReader(); reader.onload = (event) => { const content = event.target.result; const workbook = XLSX.read(content, { type: 'array' }); const sheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[sheetName]; this.excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); }; reader.readAsArrayBuffer(this.file); } else if (this.fileType === 'pdf') { const canvas = this.$refs.pdfCanvas; const ctx = canvas.getContext('2d'); pdfjsLib.getDocument(this.file).promise.then((pdf) => { pdf.getPage(1).then((page) => { const viewport = page.getViewport({ scale: 1.5 }); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: ctx, viewport, }); }); }); } }, props: { file: { type: File, required: true, }, }, created() { // 根据文件后缀名判断文件类型 const fileExtension = this.file.name.split('.').pop(); if (fileExtension === 'docx' || fileExtension === 'doc') { this.fileType = 'docx'; } else if (fileExtension === 'xls' || fileExtension === 'xlsx') { this.fileType = 'xls'; } else if (fileExtension === 'pdf') { this.fileType = 'pdf'; } }, }; </script> ``` 在上述代码中,根据文件后缀名判断文件类型,然后使用不同的库进行解析和预览。对于Word文件,使用`docx.js`库将文件解析为HTML格式,然后在Vue中显示;对于Excel文件,使用`js-xlsx`库将文件解析为JSON格式,然后在Vue中生成表格;对于PDF文件,使用`pdf.js`库将文件渲染成图片,然后在Vue中显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值