如何在用户计算机上下载响应后 API 收到的文件?

How to download a file on user's machine received in response of a post API?

提问人:Bharti Sharma 提问时间:8/2/2023 更新时间:8/2/2023 访问量:27

问:

我试图在单击按钮(ReactJs)时在用户的机器中下载文件,该按钮正在点击后API(express,nodeJs)

这是我在前端的代码。


import React from "react";
import download from 'downloadjs';

const downloadFileButton = () => {
  const downloadFile = async (e, item) => {
    e.preventDefault()
    try {
      const responseData = await fetch({
        url: `apiUrl`,
        method: 'POST',
        body: JSON.stringify({
          fileName: item.file_name,
        }),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${authToken}`
        }
      })
      if (responseData) {
        const file = await responseData.blob()
        download(file, "test.txt");
      }
    } catch (err) {
      return alert(err.message)
    }
  }
  return (
    <button to='vehicleStatus' onClick={e=>downloadHandler(e,item)}>
      <span class="material-icons-outlined green">file_download</span>
    </button>
  )
}

export default downloadFileButton;

这是我在后端的代码

const downloadSoftware = async(req, res, next) => {
  await sequelize.sync();
  let downloadfile;
  console.log(req.body)
  try{
    downloadfile = await downloadFromFtpServer(req.body.fileName)
    // above line is able to download file from ftp server successfully and store it in downloads folder
    if (downloadfile.code >= 400 || downloadfile.error) {
      console.log('err',downloadfile)
    }
    res.status(200).sendFile(path.resolve(__dirname, '../../downloads/', req.body.fileName));
  } catch(err){
    console.log(err)
    return next(err);
  }
}

这是我在前端遇到的错误 “意外的令牌 'h', 'hello2' 是无效的 JSON” 在这里你可以看到“hello2”是我从后端发送的文件的内容。

节点 .js Reactjs 文件

评论

0赞 Bharti Sharma 8/6/2023
问题解决了,多亏了@Win的回答:stackoverflow.com/a/51994070/22323982

答: 暂无答案