美文网首页
vue-pdf预览和下载,后台返回文件流(blob)

vue-pdf预览和下载,后台返回文件流(blob)

作者: M_细花儿 | 来源:发表于2021-01-26 10:40 被阅读0次

    背景:碰到了在当前页面预览pdf(不打开新的窗口,采用iframe),并下载。

    一、pdf的预览

    1.在适合位置嵌入iframe标签

      <iframe :src="pdfUrl" frameborder="0" width="100%" :style="{height: tableHeight,overflow:'auto'}"></iframe>
    

    2.在methods中添加相应方法

    pdfPreview(val) {
          this.previewDownFile(val).then(v => {
            if (v.status == 200) {
              const binaryData = [];
              binaryData.push(v.data);
              let url = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
              this.pdfUrl = url
            } else {
              this.$message.error("请求错误!");
            }
          })
        },
    
    
       previewDownFile(val) {
          return new Promise((resolve, reject) => {
            this.$axios({
              url: `file-server/download/annex/${val.value}`,
              timeout: 0,
              method: 'get',
              responseType: 'blob',
              header: {"Content-Type": "multipart/form-data"},
            }).then(res => {
              resolve(res)
            }).catch(() => {
              resolve(false);
            });
          });
        },
    

    二、pdf的下载

        pdfUpdate() {
          this.previewDown().then(v => {
            if (v.status == 200) {
              if (!v) {
                return;
              } else {
                const elink = document.createElement("a");
                // console.log(new Blob([v.data]));
                elink.href = window.URL.createObjectURL(new Blob([v.data], {type: `application/pdf`}));
                elink.style.display = 'none';
                elink.setAttribute('download', this.tabData.dataCateName);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
              }
            }
          })
        },
    
    
     previewDown() {
          return new Promise((resolve, reject) => {
            this.$axios({
              url: `file-server/download/${this.emitData.fileId}`,
              timeout: 0,
              method: 'get',
              responseType: 'blob',
              header: {"Content-Type": "multipart/form-data"},
            }).then(res => {
              resolve(res)
            }).catch(() => {
              resolve(false);
            });
          });
        },
    

    总结:其实但看代码还是蛮简单的。但是实际操作的时候,还是费了一番功夫。

    相关文章

      网友评论

          本文标题:vue-pdf预览和下载,后台返回文件流(blob)

          本文链接:https://www.haomeiwen.com/subject/htqgzktx.html