vue 通过axios下载后端接口文件流pdf文件

关于下载在页面直接写url地址也是可以下载的,

window.location.href=“text.pdf”;

但后端接口有的时候要求传给我们前端的是文件流格式,前端处理方式如下

              that.$http({
                      method:"get",
                      url:api.exportContract+'/'+agreementId+'/'+docNumber,
                      headers:headers('application/x-download'),
                      responseType: 'blob',
                  }).then(function(res){
                    let url = window.URL.createObjectURL(new Blob([res.data]));  // new Blob([data])用来创建URL的file对象或者blob对象
                          let link = document.createElement('a');
                          link.style.display = 'none';
                          link.href = url;
                               link.download= docNumber+'.pdf'; //docNumber 动态文件名
                          document.body.appendChild(link);
                          link.click();
                  });

### 在 Vue 项目中处理后端返回的 PDF 文件流 #### 使用 `Blob` 和 `URL.createObjectURL()` 显示 PDF 文件 为了在 Vue 项目中显示来自后端PDF 字节流,可以利用 JavaScript 的 `Blob` 对象以及 `URL.createObjectURL()` 方法创建临时 URL 来加载 PDF 文档。 ```javascript methods: { async showPdf() { try { const response = await axios.get('/api/pdf', { responseType: 'blob' }); const file = new Blob([response.data], { type: 'application/pdf' }); const fileURL = URL.createObjectURL(file); window.open(fileURL); // 打开新窗口展示PDF文档 } catch (error) { console.error('Failed to fetch and display the PDF:', error); } } } ``` 此方法适用于希望直接在浏览器内查看 PDF 而不是立即下载的情况[^1]。 #### 下载 PDF 文件至本地 对于需要让用户能够保存 PDF 到本地的需求,则可通过创建 `<a>` 标签并设置其属性来触发下载行为: ```html <a id="downloadLink" style="display:none;"></a> ``` ```javascript methods: { async downloadPdf() { try { const response = await axios.get('/api/pdf', { responseType: 'blob' }); const blob = new Blob([response.data], { type: 'application/pdf' }); let link = document.getElementById('downloadLink'); if (!link) { link = document.createElement('a'); link.id = 'downloadLink'; document.body.appendChild(link); } link.href = URL.createObjectURL(blob); link.download = "document.pdf"; // 设置默认文件名 link.click(); setTimeout(() => { URL.revokeObjectURL(link.href); // 清除不再使用的对象URL }, 0); } catch (error) { console.error('Error downloading the PDF:', error); } } } ``` 这段代码会先获取 PDF 数据作为二进制大对象 (`Blob`) ,然后构建一个隐藏的链接元素用于启动下载过程。当用户调用该函数时,将会弹出下载对话框允许他们选择存储位置[^2][^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值