下载从ERPweclapp的API调用接收到的PDF,该PDF使用Java语言FlateDecoded

问题描述

我打算收到一个pdf文件,以直接从API调用中下载该文件。 我回来的样子如下:

%PDF-1.4
%����
4 0 obj
<</Filter/FlateDecode/Length 983>>stream
x��Xo�0Է<ѭC�:�H�]`
����ڍ��֕n"$�

我需要怎么做才能下载此文件?我正在vuejs / axios中作为前端工作,并打算将express用作后端。

在这里发现了一个类似的问题,但没有解决办法:Download PDF file from api using javascript IE9 我实现了代码,但是结果弹出窗口仍然保持白色

通常它似乎是带有FlateDecode过滤器的pdf。

解决方法

我有这个实用程序,可以从API网址下载文件。

import axios from "axios";

/**
 * utility to download a File from an api url.
 * @param config (optional) config for axios
 */
export default function download(url,config) {
  return axios.get<Blob>(url,{
    ...config,responseType: "blob"
  }).then(response => {
    // get filename from content-disposition header
    const contentDisposition = response.headers["content-disposition"];
    const fileName = contentDisposition.match(/\bfilename=([^;]*)/)[1].trim();
    
    //"save" file to hard disk
    const link = document.createElement("a");
    link.href = URL.createObjectURL(response.data);
    link.setAttribute("download",fileName);
    document.body.appendChild(link);
    link.click();

    // cleanup
    setTimeout(() => {
      link.parentNode.removeChild(link);
    },3000);

    return response;
  })
}
,

因此我在以下线程中找到了这个可行的答案:https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

似乎有很多不同的方法可以解决这个问题。

  await this.$axios( this.api_url,{method: 'GET',responseType: 'blob',headers: {"AuthenticationToken": this.api_token} }
    ).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    // works in IE11
    if (typeof window.navigator.msSaveBlob === 'function') {
      window.navigator.msSaveBlob(
        response.data,`${filename}.pdf`
      );
    } else {
      link.setAttribute('download',`filename.pdf`);
      document.body.appendChild(link);
      link.click();
    }
});