繁体   English   中英

如何在反应中使用 fetch 方法上传文件?

[英]How do I upload a file with fetch method in react?

我正在开发一个反应组件,我想将 excel 文件上传到服务器。 这是我正在尝试的。 但是当我控制台请求正文时,它给了我一个空的 object

<input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>

这是在输入文件更改时将执行的文件处理程序方法:

fileHandler = (event) => {
        event.preventDefault();
        let fileObj = event.target.files[0];
        console.log(fileObj);
        //console.log(JSON.stringify(fileObj));

        var data = new FormData()
        data.append('file', fileObj)

        fetch("/upload", {
            method: 'POST',
            body: data
        }).then(function(response) {
            if (response.status >= 400) {
                throw new Error("Bad response from server");
            }
            return response.text();
        }).then(function(data) {
            console.log(data)
        }).catch(function(err) {
            console.log(err)
        });
}

这是上传文件的服务器代码。

app.post('/upload', function(req, res) {
        console.log(req.body); // Output : {} or undefined
        /*try {
            if(!req.files) {
                res.send({
                    status: false,
                    message: 'No file uploaded'
                });

            } else {
                let avatar = req.files.avatar;

                //Use the mv() method to place the file in upload directory (i.e. "uploads")
                avatar.mv('./uploads/' + avatar.name);

                //send response
                res.send({
                    status: true,
                    message: 'File is uploaded',
                    data: {
                        name: avatar.name,
                        mimetype: avatar.mimetype,
                        size: avatar.size
                    }
                });
            }
        } catch (err) {
            res.status(500).send(err);
        }*/
     })

如果我在下面尝试使用表单操作,它会在 req.files 中给我正确的 output 但我不想重定向。

<form id="myForm" method="post" encType="multipart/form-data" action="/upload">
  <input type="hidden" name="msgtype" value="2"/>
  <input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>
  <input type="submit" value="Upload" />
</form>

我也不想使用 axios 因为我对所有其他执行使用相同的获取请求。 任何帮助表示赞赏。

最后,我能够使用fetch处理正确的请求参数。 这是我尝试并按预期工作的解决方案:

<form id="myForm" method="post" encType="multipart/form-data" action="/upload" onSubmit={this.fileSubmit.bind(this)}>
  <input type="hidden" name="msgtype" value="2"/>
  <input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>
  <input type="submit" value="Upload" />
</form>

这是提交处理程序:

fileSubmit = (event) => {
  event.preventDefault();
  fetch(event.target.action, {
      method: 'POST',
      body: new FormData(event.target) // event.target is the form

  }).then((resp) => {
      return resp.json();
      //console.log(resp.json());

  }).then((body) => {
      // TODO handle body
      console.log(body);
      if(body.status) {
          alert(body.message);
      }
      else {
          alert("Please Select a file to upload");
      }
  }).catch((error) => {
      // TODO handle error
      //
  });

在服务器端,我可以获得req.filesreq.body

app.post('/upload', function(req, res) {
        console.log(req.body); // which gives me form data
        console.log(req.files); // which gives me file object
});

我真的不知道我在 fetch 上做错了什么,但我通过将表单的操作重定向到不可见来实现文件上传。 在这里,我可以防止表单重定向。

<iframe name="dummyframe" id="dummyframe" style={{"display": "none"}}></iframe>
<form id="myForm" method="post" encType="multipart/form-data" action="/upload" target="dummyframe">
  <input type="hidden" name="msgtype" value="2"/>
  <input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>
  <input type="submit" value="Upload" />
</form>

因此,无需获取,我将在服务器端获取文件 object,如下所示:

app.post('/upload', function(req, res) {
        console.log(req.files); // Output : {avatar:{name:"", data: "", size:"", mimetype:""}}
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM