vue文件预览功能实现

文件预览功能实现

 // 预览接口封装
 export function preview(data) {
  return request({
    url: "地址",
    method: "post",
    data: data,
    responseType: 'blob',
  })
}

实现思路:

  1. 通过文件id走接口获取预览文件流
  2. 通过 window.URL.createObjectURL 方法将预览文件流转化成图片地址
         this.previewUrl = window.URL.createObjectURL(
            new Blob([res], { type: "application/pdf" })
         );
  1. 重新设置弹框或者页面大小
   this.$nextTick(() => {
     this.$refs.pdf.height = document.documentElement.clientHeight-500;
   });

完整js代码

    // 预览
    previewLi(id){
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      preview({ Id: id }).then((res) => {
        this.previewShowPdf = true;
        if (res.code!==500) {
          loading.close();
          // 对后端返回二进制流做处理
          this.previewUrl = window.URL.createObjectURL(
            new Blob([res], { type: "application/pdf" })
          );
          console.log(this.previewUrl,'文件流地址')
          // 重新设置大小
          this.$nextTick(() => {
            this.$refs.pdf.height = document.documentElement.clientHeight-500;
          });
        } else{
          this.$message({
            type: "info",
            message: res.msg,
          });
        }
      })
    },

4.通过iframe标签指定类型,显示图片

 <el-dialog v-if="previewShowPdf" title="预览" :visible.sync="previewShowPdf" append-to-body width="90%" v-loading="loading">
      <!-- PDF显示的地方 -->
      <iframe ref="pdf" :src="previewUrl" width="100%"></iframe>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="previewShowPdf = false">关 闭</el-button>
      </span>
</el-dialog>

功能完成

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值