1

我试图将图像(ReactJs)上传到我的服务器(NodeJs+ Express+ multerJs)到数字海洋。

我使用带有 multipart/form-data 的 POST 请求;

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

当我对表单执行相同的 Post 请求而不处理表单的提交时,一切正常并且 Files 数组不为空。上面的代码正在运行:

<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 Ocean):

  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;

如果有人可以帮助我!(我已经疯狂地用谷歌搜索了,,,)谢谢!

4

3 回答 3

1

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

反应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);
      });
于 2019-11-03T07:09:08.410 回答
0

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

修改 onChange 处理程序:

方法一:

将文件放入变量并将其设置为 setState。

onChange = (e) => {

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

使用 event.persist() 的方法 2:

onChange = (e) => {
         e.persist();
         this.setState({ file: e.target.files[0] });
    };
于 2019-11-03T06:20:39.553 回答
0

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

于 2019-11-02T13:17:51.047 回答