vue实现预览PDF、Excel、Docx、Txt、PPT文件的功能

文章展示了如何在Vue.js应用中结合ElementUI组件库,通过iframe和预览功能,实现对word、excel、pdf、txt等不同类型的文件进行预览。利用微软的在线OfficeApps服务,可以对特定文件格式如docx和xlsx进行预览。用户点击文件名或预览按钮后,会弹出预览对话框,其中iframe加载相应的文件内容。

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

目录:

        一、实现步骤

        二、实现效果

代码真实可用!

一、实现步骤:

1、使用的是vue和elementUI,

假设有这些变量:attachment是附件的意思

data() {
     return {
            previewDialog: false,
            attachmentSrc: '',

            attachmentList: [{
                 name: 'example1.docx',
                 path: 'https://vfdgfdsgdfsgfg/attachment/example1.docx'
             },
             {
                 name: 'example2.pdf',
                path: 'https://vfdgfdsgdfsgfg/attachment/example2.pdf'
             },
             {
                 name: 'example3.txt',
                 path: 'https://vfdgfdsgdfsgfg/attachment/example3.txt'
             },
             {
                 name: 'example4.xlsx',
                  path: 'https://vfdgfdsgdfsgfg/attachment/example4.xlsx'
             }]
        }
  }

2、页面代码:

主要是用 iframe 组件,src地址即为要展示的文件地址

<!-- 这段代码是界面显示 -->
<div v-for="attachment in attachmentList">
      <el-link :key="attachment.path" :href="attachment.path"
           style="display: inline-block;"  type="success" :underline="false">
         {{ attachment.name }}
      </el-link>
     <el-button type="text" style="display:inline-block;margin-left:30px;" 
        icon="el-icon-view" v-on:click="previewFile(attachment)">
        预览</el-button>
</div>



<!-- 点击上面的预览按钮会弹出文件预览框 -->
<el-dialog :close-on-click-modal="true" title="文件预览" type="primary"             
   :visible.sync="previewDialog"  width="80%" left>
    <iframe :src="attachmentSrc" frameborder="0" width="100%" height="600"></iframe>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-on:click="previewDialog = false">关闭</el-button>
    </div>
</el-dialog>

3、methods中的函数:

word、xls、ppt这些文件要用 微软官方的预览地址

注意:1. 文件地址必须公网;2. 静态资源不要有访问权限

最后,你控制的只是src地址

微软解析地址:https://view.officeapps.live.com/op/view.aspx?src=你的文件地址

methods: {
    // 预览文件
    previewFile(attachment) {// 根据文件格式显示预览内容
         const fileExtension = attachment.path.split('.').pop().toLowerCase()
         if (fileExtension === 'xlsx' || fileExtension === 'docx') {
            this.attachmentSrc = 'https://view.officeapps.live.com/op/view.aspx?src=' + attachment.path
         }else{
             this.attachmentSrc = attachment.path
         }
        this.previewDialog = true
    }
}



二、实现效果:

操作界面:

word文件预览:

Excel文件预览;

PDF文件预览:

 TXT文件预览:

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值