How to download fetch response in react as file

后端 未结 5 1131
不知归路
不知归路 2020-12-07 21:02

Here is the code in actions.js

export function exportRecordToExcel(record) {
    return ({fetch}) => ({
        type: EXPORT_RECORD_TO_EXCEL,         


        
5条回答
  •  醉梦人生
    2020-12-07 21:09

    You can use these two libs to download files http://danml.com/download.html https://github.com/eligrey/FileSaver.js/#filesaverjs

    example

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

提交回复
热议问题