在React / Node中使用API​​调用发送和接收文件

时间:2019-03-06 21:34:11

标签: node.js reactjs express

我正在尝试构建一个React应用程序,该应用程序上传一个文件,在后端对其进行处理,然后返回要在前端下载的文件。我已经在后端成功接收了文件,现在试图弄清楚如何将响应文件发送回要下载的前端,但是不确定如何发送该文件或在客户端中接收它。 / p>

//FRONTEND

async uploadFiles() {
  this.setState({uploadProgress: {},uploading: true});
  const promises = [];
  this.state.files.forEach(file => {
    promises.push(this.sendRequest(file));
  });
  try {
    await Promise.all(promises);

    this.setState({successfullUploaded: true,uploading: false});
    window.setTimeout(() => {
      this.props.closeUpload('finished')
    }, 2000)
  } catch (e) {
    // Not Production ready! Do some error handling here instead...
    this.setState({successfullUploaded: true,uploading: false});
  }
}


//BACKEND

module.exports = function upload(req, res) {
  var form = new IncomingForm();

  form.on("file", (field, file) => {
    // Do something with the file
    // e.g. save it to the database
    // you can access it using file.path
    console.log(file.path)
    localPathOrig = 'files/midi.mid'
    localPathResp = 'files/chords.mid'
    fs.copyFile(file.path, localPathOrig, console.log)
    fs.copyFile(localPathOrig, localPathResp, console.log)
    //do things to file 'localPathResp'
  });
  form.on("end", () => {
    res.writeHead(200, {
      "Content-Type": "application/octet-stream",
      "Content-Disposition": "attachment; filename=" + localPathResp
    });
    fs.createReadStream(localPathResp).pipe(res);
  });
  form.parse(req);
};

0 个答案:

没有答案