目录:

        一、实现步骤

        二、实现效果

代码真实可用!

一、实现步骤:

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文件预览:

Logo

前往低代码交流专区

更多推荐