后台返回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);
      });
    },
posted @     阅读(375)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示