向服务器获取 /POST 请求:接收 multipart/form-data 时为空数组;

Fetch /POST request to Server: Empty array when receiving multipart/form-data;

我正在尝试将图像 (ReactJs) 上传到我的服务器 (NodeJs+ Express+ multerJs) 到 digital Ocean。

我正在使用 POST 请求 multipart/form-data;

我从 multerJs 收到一条成功消息,但我可以在服务器的日志中看到文件:[] 有一个空数组。而且那个Digital Ocean当然没有添加任何文件。

当我对表单执行相同的 Post 请求而不处理表单的提交时,一切正常,文件数组不正常 empty.the 上面的代码正常工作:

<form method="post" enctype="multipart/form-data" action="http://localhost:3004/upload_image_test_4"   >    </form>

客户端 React.js :

export default class Select_size extends React.Component {
on_form_submit = (e) => {
    e.preventDefault();
    const fileInput = this.state.file;
    const formData = new FormData();
    formData.append('file', fileInput);
    const options = {
        method: 'POST',
        body: formData,
        headers: {
            'Access-Control-Allow-Origin': '*',
             Accept: 'application/json',
            'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
        }
    };
    var url =
        this.state.action_link +
        '?url=' +
        this.state.id_user +
        '/' +
        this.state.id_draft +
        '&name=' +
        this.state.name_file;
    fetch(url, options);
};

onChange = (e) => {
    this.setState({ file: e.target.files[0] });
};

 constructor(props) {
    super(props);
    this.state = {
  files: [],
  };
this.onChange = this.onChange.bind(this);
  }
render() {
    return (  
<form onSubmit={this.on_form_submit} enctype="multipart/form-data">
                    <input type="file" name="myImage" onChange={this.onChange} />
                    <button type="submit">Upload</button>
</form>

  )}

}

服务器端(Node.js/ExpressJs/Multer/Digital海洋):

  const express = require('express');
  const router = express.Router();
  const bodyParser = require('body-parser');
  const aws = require('aws-sdk');
  const spacesEndpoint = new aws.Endpoint('fra1.digitaloceanspaces.com');
  const s3 = new aws.S3({
  endpoint: spacesEndpoint,
  accessKeyId: 'myID',
  secretAccessKey: 'MySecretKey'
  });
  const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'bucketName',
    acl: 'public-read',
    key: function(request, file, cb) {
        cb(null, urlBucket + name_image);
        }
   })
   }).array('upload', 1);

  router.post('/upload_image_test_4', function(request, response, next) {
  upload(request, response, function(error) {
    console.log(request, 'the request');
    if (error) {
        console.log(error);
        return response.json(error, 'error');
    }
    console.log('File uploaded successfully.');
    return response.json('success its uploaded to digital ocean');
});

});
module.exports = router;

如果有人可以帮助我! (我已经疯狂'googled',) 谢谢!!

输入的文件不是数组而是 FileArray,尝试 [...e.target.files][0]

与 React 中的事件池和 setState 的异步行为相关。

修改 onChange 处理程序:

方法一:

将文件放入变量中,并在setState中设置。

onChange = (e) => {

      const uploadFile = e.target.files[0] ;
      this.setState({ file: uploadFile  });
};

方法 2 event.persist():

onChange = (e) => {
         e.persist();
         this.setState({ file: e.target.files[0] });
    };

//编辑我找到了我自己的问题的解决方案......在 github 页面上专门针对与 Next.js 相关的错误: 由于某些原因,该文件未发送到请求。 我以这种方式使用了 axios,它现在可以工作了:

React-js:

    sendFile = (e) => {
      const data = new FormData();
      const file = e.target.files[0];
      data.append('avatar', file);
     axios
            .post('http://localhost:3004/upload_test_stack_2', data)
            .then(console.log)
          .catch(console.error);  

      }

服务器端(nodeJs):

const upload = multer({
    storage: multerS3({
    s3: s3,
    bucket: 'My Bucket',
    acl: 'public-read',
    key: function(request, file, cb) {


        cb(null, file.originalname);
    }
    })

});

router.post('/upload_test_stack_2', upload.single('avatar'), (req, res) 
 =>      {

    console.log(req.file, 'The file appears here');
    return res.sendStatus(200);
      });