以字节流的形式下载 PDF

use*_*404 4 javascript pdf reactjs reactjs-flux

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

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

调试后正在正确获取流,但下载文件会产生错误: 加载 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
  }
Run Code Online (Sandbox Code Playgroud)

处理响应:

  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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

同样的错误。

Car*_*ado 7

也许您的问题与在客户端处理 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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

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

但是,最简单的方法是@drinchev 提到的,只需将其服务器放在 URL 中即可。