下载PDF作为字节流

时间:2017-08-14 10:55:05

标签: javascript reactjs pdf reactjs-flux

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

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);
    }
  }

同样的错误。

3 个答案:

答案 0 :(得分:2)

也许您的问题与客户端处理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将被下载并显示在浏览器的新窗口中。

然而,最简单的方法是@drinchev提到的,只是在URL中将它服务器就是这样。

答案 1 :(得分:0)

如果你可以在后端工作,

然后这个answer可能会有所帮助......

答案 2 :(得分:0)

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

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);
        }