【问题标题】:REST API EXPRESS JS: Can not download file in Reactjs, which is send by back-endREST API EXPRESS JS:无法在 Reactjs 中下载文件,这是由后端发送的
【发布时间】:2020-03-28 22:00:26
【问题描述】:

我使用 Express JS 创建了 REST API 来发送 Excel 文件:


app.get('/download/', async (req, res) => {
    try {
       await res.download('./ExcelCopy.xlsx');
    } catch (e) {
        res.status(400).send(e);
    }
});

但是在 Reactjs 中,当我连接到 API 时什么都没有发生,但是 redux 告诉我一切都很顺利:

export const getExcel = () => async (dispatch) => {
  await dispatch(getExcelRequest());
  try {
    await axios.get('http://127.0.0.1:8888/download/');
    dispatch(getExcelSuccess());
  } catch (error) {
    console.log(error);
    dispatch(getExcelFailed());
  }
};

我应该怎么做才能使用 react js 从后端下载文件

【问题讨论】:

标签: node.js reactjs rest api express


【解决方案1】:

你需要添加response type并使用npm包file-saver下载文件。

修改代码:

export const getExcel = () => async (dispatch) => {
  await dispatch(getExcelRequest());
  try {
    axios.get('http://127.0.0.1:8888/download/', { responseType: 'arraybuffer' })
      .then((response) => {
         var blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
              fileSaver.saveAs(blob, 'data.xlsx');
              dispatch(getExcelSuccess());

       });        
 } catch (error) {
    console.log(error);
    dispatch(getExcelFailed());
}

};

【讨论】:

    【解决方案2】:

    据我所知,您不能只发送一个获取请求来下载文件。相反,我建议你使用这个名为 js-file-download 的模块。

    示例用法:

    const FileDownload = require('js-file-download');
    
    const response = await axios.get('http://127.0.0.1:8888/download/')
    FileDownload(response.data, 'ExcelCopy.xlsx');
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2020-06-18
      • 2020-11-18
      • 2019-01-14
      • 2021-06-24
      • 2021-09-08
      相关资源
      最近更新 更多