gaoluyang
2 天以前 b871888a4ee32d15adfd52fdfabc44c7c674db0e
src/components/Preview/filePreview.vue
@@ -4,10 +4,10 @@
      <img :src="imgUrl" alt="Image Preview" />
    </div>
    <div v-if="isPdf" style="height: 80vh;">
<!--      <object :data="fileUrl" type="application/pdf" width="100%" height="750px">-->
<!--        <p>您的浏览器不支持 PDF 预览。<a :href="fileUrl" style="color: #3a7bfa;" target="_blank">下载 PDF 文件</a></p>-->
<!--      </object>-->
      <onlyoffice ref="onlyoffice" :options="option" style="width: 100%;height: 100%;" />
      <onlyoffice v-if="useOnlyOffice" ref="onlyoffice" :options="option" style="width: 100%;height: 100%;" />
      <iframe v-else-if="pdfUrl" :src="pdfUrl" title="PDF 预览" style="width: 100%;height: 100%;border: none;"></iframe>
      <p v-else-if="pdfError">PDF 预览失败,<a :href="fileUrl" style="color: #3a7bfa;" target="_blank">点此下载查看</a></p>
      <p v-else>正在加载 PDF…</p>
    </div>
    <div v-if="isDoc">
      <p v-if="!isDocShow">文档无法直接预览,请下载查看。</p>
@@ -53,6 +53,7 @@
</template>
<script>
import axios from 'axios'
import VueOfficeDocx from '@vue-office/docx'
//引入相关样式
import '@vue-office/docx/lib/index.css'
@@ -92,7 +93,9 @@
        transformData: (workbookData) => { return workbookData }, //将获取到的excel数据进行处理之后且渲染到页面之前,可通过transformData对即将渲染的数据及样式进行修改,此时每个单元格的text值就是即将渲染到页面上的内容
      },
      csvList: [],//csv文件数据
      imgUrl: ''
      imgUrl: '',
      pdfUrl: '',       //pdf本地预览地址
      pdfError: false,
    }
  },
  computed: {
@@ -134,9 +137,46 @@
    },
    isSupported() {
      return this.isImage || this.isPdf || this.isDoc || this.isZipOrRar || this.isCsv || this.isXls;
    }
    },
    // 调用方传了 OnlyOffice 的配置才走文档服务,否则用浏览器内置阅读器
    useOnlyOffice() {
      return !!(this.option && this.option.url);
    },
  },
  watch: {
    fileUrl: {
      handler() {
        this.loadPdf();
      },
      immediate: true,
    },
  },
  beforeDestroy() {
    this.releasePdfUrl();
  },
  methods: {
    releasePdfUrl() {
      if (this.pdfUrl) {
        URL.revokeObjectURL(this.pdfUrl);
        this.pdfUrl = "";
      }
    },
    async loadPdf() {
      this.releasePdfUrl();
      this.pdfError = false;
      if (!this.isPdf || this.useOnlyOffice) {
        return;
      }
      try {
        const { data } = await axios.get(this.fileUrl, { responseType: "blob" });
        // 后端返回的 Content-Type 不一定带 application/pdf,这里强制指定,
        // 浏览器才会用内置阅读器打开而不是直接下载
        this.pdfUrl = URL.createObjectURL(new Blob([data], { type: "application/pdf" }));
      } catch (error) {
        console.error(error);
        this.pdfError = true;
      }
    },
    renderedHandler() {
      console.log("渲染完成")
      this.isDocShow = true