index.vue 2.41 KB
<template>
    <div class="attachment-preview">
      <el-card>
        <template v-if="loading">
          正在加载...
        </template>
        <template v-else>
          <!-- PDF 预览 -->
          <div v-if="isPdf">
            <vue-office-pdf
            :src="docx"
            style="height: 60vh"
            @rendered="rendered"
            :key="fileId"
            />
          </div>
  
          <!-- 图片预览 -->
          <div v-else-if="isImage">
            <el-image :src="previewUrl" style="height: 60vh"/>
          </div>
  
          <!-- 不支持的类型 -->
          <div v-else>
            <p>当前附件类型不支持预览。</p>
          </div>
        </template>
      </el-card>
    </div>
  </template>
  
  <script>
  //import pdf  from 'vue-pdf';
  import VueOfficePdf from '@vue-office/pdf';
  export default {
    name: "AttachmentPreview",
    components: {
      //pdf,
      VueOfficePdf
    },
    props: {
      fileId: {
        type: String,
        required: false,
      },
      fileType: {
        type: String,
        required: true,
      },
      filePath: {
        type: String,
        required: false,
      }
    },
    data() {
      return {
        docx: "",
        loading: true,
      };
    },
    computed: {
      isPdf() {
        return this.fileType === "pdf";
      },
      isImage() {
        return ["jpg", "jpeg", "png", "gif", "bmp"].includes(this.fileType);
      },
    },
    mounted() {
      this.loadPreview();
    },
    watch: {
      fileId(newVal) {
        this.loadPreview();
      }
    },
    methods: {
      /**
       * 加载附件预览 URL
       */
      loadPreview() {
        this.previewUrl = process.env.VUE_APP_BASE_API+"/view/attachement/preview?id=" + this.fileId;
        if(this.filePath != '' && this.filePath != null) {
          this.previewUrl = process.env.VUE_APP_BASE_API+"/view/attachement/preview?path=" + this.filePath;
        }
        console.log(this.previewUrl);
        fetch(this.previewUrl)
        .then(response => response.blob())
        .then(blob => {
          this.docx = blob;
        });
        this.loading = false;
      },
      /**
       * 根据文件路径获取文件类型
       */
      getFileType() {
        return this.fileType;
      },
      rendered(){
            //console.log("渲染完成")
        },
    },
  };
  </script>
  
  <style>
  .attachment-preview {
    padding: 0px;
  }
  </style>