如何下载获取响应作为文件反应

How to download fetch response in react as file

这是actions.js

中的代码
export function exportRecordToExcel(record) {
    return ({fetch}) => ({
        type: EXPORT_RECORD_TO_EXCEL,
        payload: {
            promise: fetch('/records/export', {
                credentials: 'same-origin',
                method: 'post',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            }).then(function(response) {
                return response;
            })
        }
    });
}

返回的响应是一个 .xlsx 文件。我希望用户能够将其保存为文件,但没有任何反应。我假设服务器正在返回正确类型的响应,因为在控制台中它显示

Content-Disposition:attachment; filename="report.xlsx"

我错过了什么?在reducer中应该做什么?

浏览器技术目前不支持直接从 Ajax 请求下载文件。解决方法是添加一个隐藏表单并在后台提交它以使浏览器触发“保存”对话框。

我是 运行 一个标准的 Flux 实现,所以我不确定确切的 Redux (Reducer) 代码应该是什么,但我刚刚为文件下载创建的工作流程是这样的......

  1. 我有一个名为 FileDownload 的 React 组件。这个组件所做的就是呈现一个隐藏的表单,然后在 componentDidMount 内立即提交表单并调用它的 onDownloadComplete prop.
  2. 我有另一个 React 组件,我们将其称为 Widget,下载 button/icon(实际上很多……table 中的每个项目一个)。 Widget有相应的动作和存储文件。 Widget 进口 FileDownload.
  3. Widget有两种下载相关的方法:handleDownloadhandleDownloadComplete.
  4. Widget 商店有一个名为 downloadPath 的 属性。默认设置为 null。当它的值设置为 null 时,没有正在进行的文件下载并且 Widget 组件不呈现 FileDownload 组件。
  5. 单击 Widget 中的 button/icon 会调用 handleDownload 方法,该方法会触发 downloadFile 操作。 downloadFile 操作不会发出 Ajax 请求。它向商店发送 DOWNLOAD_FILE 事件,同时发送 downloadPath 以下载文件。商店保存 downloadPath 并发出更改事件。
  6. 由于现在有一个 downloadPathWidget 将渲染 FileDownload 传递必要的道具,包括 downloadPath 以及 handleDownloadComplete 方法onDownloadComplete.
  7. 的值
  8. 当呈现 FileDownload 并使用 method="GET"(POST 也应该有效)和 action={downloadPath} 提交表单时,服务器响应现在将触发浏览器的保存目标下载文件的对话框(在 IE 9/10、最新的 Firefox 和 Chrome 中测试)。
  9. 表单提交后,立即调用 onDownloadComplete/handleDownloadComplete。这会触发另一个调度 DOWNLOAD_FILE 事件的操作。但是,这次 downloadPath 设置为 null。商店将 downloadPath 保存为 null 并发出更改事件。
  10. 由于不再有 downloadPath FileDownload 组件不会在 Widget 中呈现,世界是一个快乐的地方。

Widget.js - 仅部分代码

import FileDownload from './FileDownload';

export default class Widget extends Component {
    constructor(props) {
        super(props);
        this.state = widgetStore.getState().toJS();
    }

    handleDownload(data) {
        widgetActions.downloadFile(data);
    }

    handleDownloadComplete() {
        widgetActions.downloadFile();
    }

    render() {
        const downloadPath = this.state.downloadPath;

        return (

            // button/icon with click bound to this.handleDownload goes here

            {downloadPath &&
                <FileDownload
                    actionPath={downloadPath}
                    onDownloadComplete={this.handleDownloadComplete}
                />
            }
        );
    }

widgetActions.js - 仅部分代码

export function downloadFile(data) {
    let downloadPath = null;

    if (data) {
        downloadPath = `${apiResource}/${data.fileName}`;
    }

    appDispatcher.dispatch({
        actionType: actionTypes.DOWNLOAD_FILE,
        downloadPath
    });
}

widgetStore.js - 仅部分代码

let store = Map({
    downloadPath: null,
    isLoading: false,
    // other store properties
});

class WidgetStore extends Store {
    constructor() {
        super();
        this.dispatchToken = appDispatcher.register(action => {
            switch (action.actionType) {
                case actionTypes.DOWNLOAD_FILE:
                    store = store.merge({
                        downloadPath: action.downloadPath,
                        isLoading: !!action.downloadPath
                    });
                    this.emitChange();
                    break;

FileDownload.js
- 完整、功能齐全的代码可供复制和粘贴
- React 0.14.7 与 Babel 6.x ["es2015", "react", "stage-0"]
- 表格必须是 display: none,这就是 "hidden" className 用于

的形式
import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';

function getFormInputs() {
    const {queryParams} = this.props;

    if (queryParams === undefined) {
        return null;
    }

    return Object.keys(queryParams).map((name, index) => {
        return (
            <input
                key={index}
                name={name}
                type="hidden"
                value={queryParams[name]}
            />
        );
    });
}

export default class FileDownload extends Component {

    static propTypes = {
        actionPath: PropTypes.string.isRequired,
        method: PropTypes.string,
        onDownloadComplete: PropTypes.func.isRequired,
        queryParams: PropTypes.object
    };

    static defaultProps = {
        method: 'GET'
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).submit();
        this.props.onDownloadComplete();
    }

    render() {
        const {actionPath, method} = this.props;

        return (
            <form
                action={actionPath}
                className="hidden"
                method={method}
            >
                {getFormInputs.call(this)}
            </form>
        );
    }
}

您可以使用这两个库来下载文件http://danml.com/download.html https://github.com/eligrey/FileSaver.js/#filesaverjs

例子

//  for FileSaver
import FileSaver from 'file-saver';
export function exportRecordToExcel(record) {
      return ({fetch}) => ({
        type: EXPORT_RECORD_TO_EXCEL,
        payload: {
          promise: fetch('/records/export', {
            credentials: 'same-origin',
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
          }).then(function(response) {
            return response.blob();
          }).then(function(blob) {
            FileSaver.saveAs(blob, 'nameFile.zip');
          })
        }
      });

//  for download 
let download = require('./download.min');
export function exportRecordToExcel(record) {
      return ({fetch}) => ({
        type: EXPORT_RECORD_TO_EXCEL,
        payload: {
          promise: fetch('/records/export', {
            credentials: 'same-origin',
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
          }).then(function(response) {
            return response.blob();
          }).then(function(blob) {
            download (blob);
          })
        }
      });

我也遇到过同样的问题。 我已经通过在空 link 上创建并引用它来解决它,如下所示:

linkRef = React.createRef();
render() {
    return (
        <a ref={this.linkRef}/>
    );
}

在我的 fetch 函数中我做了这样的事情:

fetch(/*your params*/)
    }).then(res => {
        return res.blob();
    }).then(blob => {
        const href = window.URL.createObjectURL(blob);
        const a = this.linkRef.current;
        a.download = 'Lebenslauf.pdf';
        a.href = href;
        a.click();
        a.href = '';
    }).catch(err => console.error(err));

基本上我已将 blob url(href) 分配给 link,设置下载属性并强制单击 link。 据我所知,这是@Nate 提供的答案的 "basic" 想法。 我不知道这样做是否是个好主意...我做到了。

我只需要在点击时下载一个文件,但我需要 运行 一些逻辑来获取或计算文件所在的实际 url。我也不想使用任何反反应命令模式,比如设置一个 ref 并在我拥有资源 url 时手动单击它。我使用的声明模式是

onClick = () => {
  // do something to compute or go fetch
  // the url we need from the server
  const url = goComputeOrFetchURL();

  // window.location forces the browser to prompt the user if they want to download it
  window.location = url
}

render() {
  return (
    <Button onClick={ this.onClick } />
  );
}

我设法下载了其余 API URL 生成的文件,使用这种代码在我的本地运行得很好:

    import React, {Component} from "react";
    import {saveAs} from "file-saver";

    class MyForm extends Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        let queryParam = buildQueryParams(form.elements);

        let url = 'http://localhost:8080/...whatever?' + queryParam;

        fetch(url, {
            method: 'GET',
            headers: {
                // whatever
            },
        })
            .then(function (response) {
                    return response.blob();
                }
            )
            .then(function(blob) {
                saveAs(blob, "yourFilename.xlsx");
            })
            .catch(error => {
                //whatever
            })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="whateverFormId">
                <table>
                    <tbody>
                    <tr>
                        <td>
                            <input type="text" key="myText" name="myText" id="myText"/>
                        </td>
                        <td><input key="startDate" name="from" id="startDate" type="date"/></td>
                        <td><input key="endDate" name="to" id="endDate" type="date"/></td>
                    </tr>
                    <tr>
                        <td colSpan="3" align="right">
                            <button>Export</button>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </form>
        );
    }
}

function buildQueryParams(formElements) {
    let queryParam = "";

    //do code here
    
    return queryParam;
}

export default MyForm;

这对我有用。

const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};

fetch(`${url}`, requestOptions)
.then((res) => {
    return res.blob();
})
.then((blob) => {
    const href = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = href;
    link.setAttribute('download', 'config.json'); //or any other extension
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
})
.catch((err) => {
    return Promise.reject({ Error: 'Something Went Wrong', err });
})