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

本文介绍了如何在Vue应用中使用ElementUI组件,通过iframe实现文件(如xlsx和docx)的在线预览,同时提及了使用微软官方预览地址的要求和限制。

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

代码真实可用!

一、实现步骤:

1、使用的是vue和elementUI,

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

	 data() {
	     return {
	            previewDialog: false,
	            attachmentSrc: '',
		 		attachmentList: [{
			        name: '75bf8e9.xlsx',
			        path: 'https://img.j7w5.com/prod/20230904/75bf8e9872064dcb31884508cc945f82.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
    }
}

二、实现效果:

在这里插入图片描述

Excel文件预览;

在这里插入图片描述
其他pdf,docx,txt,ppt 格式文件找不到外网的地址,没有加上去测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值