后台返回pdf文件流,前端实现在线预览和下载

预览功能

用到的data值:

data(){
        return{
           fileUrl: null,
           dialogTitlePdf:'',
           dialogVisiblePdf:false,
           disabledPdf:false,
    }
}


预览的弹框:

<el-dialog 
    :title="dialogTitlePdf" 
    :visible.sync="dialogVisiblePdf"
     width="900px" 
    custom-class="loadingBox">
    <iframe  :src="fileUrl" width="100%" height="600px"></iframe>
</el-dialog>

点击事件:

<el-button @click="handlePreview" size="mini" type="text">预览</el-button>

事件:

handlePreview(){
   this.dialogTitlePdf = "预览";
   this.dialogVisiblePdf  = true;
   this.disabledPdf = false;

   getWord2PdfByte().then((res) => {
      const contentType = res.headers ? res.headers['content-type'] : 'application/pdf'; // 如果没有 content-type,使用默认值
      const fileBlob = new Blob([res], { type: contentType});
       this.fileUrl = URL.createObjectURL(fileBlob);
   }).catch((error) => {
              console.error('文件预览失败:', error);
   });
},

下载 

<el-button @click="handleDownload" size="mini" type="text">下载</el-button>

handleDownload(row) {   
        // 使用对象a存放文件的信息
    getWord2PdfByte().then((res) => {
        // 检查 res.headers 是否存在,并确保 PDF 文件的 content-type
        const contentType = res.headers && res.headers['content-type'] ? res.headers['content-type'] : 'application/pdf';

        // 创建 Blob 对象
        const blob = new Blob([res], { type: contentType });
        const fileName = row.fileName || 'downloaded_file.pdf'; // 如果没有文件名,使用默认名

        // 判断是否支持 'download' 属性
        if ('download' in document.createElement('a')) {
          // 创建隐藏的 <a> 元素
          const elink = document.createElement('a');
          elink.download = fileName;  // 设置文件名
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);  // 创建 Blob 对象 URL
          document.body.appendChild(elink);  // 将 <a> 元素添加到文档中
          elink.click();  // 自动触发点击事件下载文件
          URL.revokeObjectURL(elink.href);  // 释放 URL 对象
          document.body.removeChild(elink);  // 从文档中移除 <a> 元素
        } else if (navigator.msSaveBlob) {
          // IE 10+ 浏览器的下载方式
          navigator.msSaveBlob(blob, fileName);
        } else {
          console.error('该浏览器不支持文件下载');
        }
      }).catch((error) => {
        console.error('文件下载失败:', error);
      });
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值