以字节流形式下载 PDF

Dowload PDF as a stream of bytes

我有 Web API,它以字节流形式提供存储文件。响应已经获取并保存在状态中,但现在我想从我的反应应用程序 onClick 按钮下载文件。我这样做如下:

downloadContract( binaryData ) {
        const file = new Blob([binaryData], { type: 'application/pdf' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      }

调试后正在正确获取流,但下载文件时出现错误: 加载 PDF 文档时出错。

更新:

使用此来源的新端点调用:

  callLoadContract: {
    remote( state, id, contractId ) {
      const url = `${base}/vendor/${id}/${contractId }`;
      return $http.instance.api.get( url, id, contractId);
    },
    success: Actions.contractLoaded,
    error: Actions.fail
  }

处理响应:

  loadContract({id, contractId}) {
    this.getInstance().callLoadContract( id, contractId );
  }

  contractLoaded( response ) {
    if (response && response.data) {
      console.log(response);
      const file = new Blob([response.data], { type: 'application/pdf' });
      const fileURL = URL.createObjectURL(file);
      window.open(fileURL);
    }
  }

同样的错误。

也许您的问题与在客户端处理 PDF 的方式无关,因为您的代码运行良好:

import React from 'react';

export default class App extends React.Component {
    constructor(props, context) {
        super(props, context);
    }

    downloadContract() {
        var oReq = new XMLHttpRequest();

        var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";

        oReq.open("GET", URLToPDF, true);

        oReq.responseType = "blob";

        oReq.onload = function() {
            // Once the file is downloaded, open a new window with the PDF
            // Remember to allow the POP-UPS in your browser
            const file = new Blob([oReq.response], { type: 'application/pdf' });

            const fileURL = URL.createObjectURL(file);

            window.open(fileURL, "_blank");
        };

        oReq.send();
    }

    render() {
        return (
            <div>
                <input type="button" onClick={this.downloadContract} value="Download PDF File"/>
            </div>
        );
    }
}

正如预期的那样,当用户单击“下载”时,PDF 将被下载并显示在新的 Window 浏览器中。

然而,最简单的方法是@drinchev 提到的,只需将它放在 URL 中即可。

这是我下载文件但不路由到新页面的解决方案:

try {
            let httpClient = new XMLHttpRequest();
            let pdfLink = "http://localhost/";
            httpClient.open('get', pdfLink, true);
            httpClient.responseType = "blob";
            httpClient.onload = function() {
                const file = new Blob([httpClient.response], { type: 'application/pdf' });
                const fileURL = URL.createObjectURL(file);
                const link = document.createElement("a");
                link.href = fileURL;
                link.download = "fileName.pdf";
                link.click();
                // document.body.removeChild(link);
                URL.revokeObjectURL(fileURL);
            };
            httpClient.send();
        } catch (e) {
            console.log(e);
        }