【问题标题】:How to parse an object sent from react frontend in express.js?如何解析从 express.js 中的反应前端发送的对象?
【发布时间】:2018-04-11 17:02:43
【问题描述】:

所以在我的 react 前端中,我使用了“react-drop-to-upload”模块来允许用户拖动文件并上传。我按照 npm 模块页面上的示例创建了一个名为 handleDrop 的处理程序。代码如下:

    handleDrop(files) {
      var data = new FormData();

      alert((files[0]) instanceof File);
      files.forEach((file, index) => {
        data.append('file' + index, file);
      });

      fetch('/file_upload', {
        method: 'POST',
        body: data
      });
    }

在我的快递后端,我有以下代码:

app.post('/file_upload', function(req , res){
  var body = '';
  req.on('data', function (data) {
      body += data;
        });
  var post = "";
  req.on('end', function () {
      //post = qs.parse(body);
      console.log(body);
      // this won't create a buffer for me
      //var fileBuffer = new Buffer(body);
      //console.log(fileBuffer.toString('ascii'));
      //pdfText(body,  function(err, chunks) {
          //console.log(chunks);
      //});
  });

  //console.log(typeof post);
});

如果我删除一个 txt 文件并在正文上进行控制台日志,它会给我:

------WebKitFormBoundaryqlp9eomS0BxhFJkQ

Content-Disposition: form-data; name="file0"; filename="lec16.txt"
Content-Type: text/plain

The content of my data!
------WebKitFormBoundaryqlp9eomS0BxhFJkQ--

我正在尝试使用 pdfText 模块,它接收 pdf 文件的缓冲区或路径名,从中提取文本到文本数组中 'chunks' 。我想使用 var fileBuffer = new Buffer(body); 将 body 对象转换为缓冲区但这行不通。有人可以帮我弄这个吗?谢谢!

【问题讨论】:

    标签: javascript reactjs express


    【解决方案1】:

    您需要一个解析器来处理多部分数据。您可以查看multer

    为您提供示例代码,

    app.post('/file_upload', function(req , res){
      var storage = multer.diskStorage({
            destination: tmpUploadsPath
        });
        var upload = multer({
            storage: storage
        }).any();
    
        upload(req, res, function(err) {
            if (err) {
                console.log(err);
                return res.end('Error');
            } else {
                console.log(req.body);
                req.files.forEach(function(item) {
                    // console.log(item);
                    // do something with the item,
                    const data = fs.readFileSync(item.path);
                    console.log(data);
                });
                res.end('File uploaded');
            }
        });
    });
    

    要深入了解示例代码,请前往here。请记住,您将获得文件数据作为缓冲区而不是实际数据。

    【讨论】:

    • 非常感谢。示例代码就像一个魅力。我肯定会详细阅读文档。再次感谢您的帮助!
    猜你喜欢
    • 2022-11-26
    • 2019-03-17
    • 2014-04-18
    • 2021-11-22
    • 2017-12-10
    • 1970-01-01
    • 2015-06-02
    • 2021-08-13
    • 2019-07-20
    相关资源
    最近更新 更多