【问题标题】:Cannot append to formData object on file upload in React在 React 中的文件上传时无法附加到 formData 对象
【发布时间】:2017-11-03 02:48:59
【问题描述】:

我是新来的反应,我正在尝试将文件上传到我的节点后端,但我已经花了一段时间并且无法让它工作。我似乎正确地将数据发送到我的句柄函数,但之后我无法将其附加到我的 formData 对象。

这是我在上传 html 中对句柄提交按钮调用的函数。

 uploadAction(){
    var self = this;
    console.log('inside uploadAction');

    var data = new FormData();
    // var filedata = {};
    var filedata = document.querySelector('input[type="file"]').files[0];

    data.append('file', filedata);

    console.log('this is the value of data in uploadAction ', data);
    console.log('this is the value of filedata in uploadAction ', filedata)

    const config = { headers: { 'Content-Type': 'multipart/form-data' } };
     axios.post('http://localhost:5000/upload',{
       filedata: data
     },config)
       .then((response)=>{
         console.log('back again success from upload');
       })
       .catch((err)=>{
         console.error('error from upload ', err);
       });

所以当我控制台注销数据和文件数据对象时,我得到以下结果。

this is the value of data in uploadAction  FormData {}

this is the value of filedata in uploadAction  File {name: "suck.jpg"....

因此,不知何故,我的文件数据似乎被正确引入,但在如何将其附加到数据对象方面存在脱节。我觉得很困惑,因为这似乎是我通过在线查看这些东西而发现附加此数据对象的方式。我认为我的 axios 调用是正确的,但在此之前我当然会遇到错误。

有人对我如何解决这个问题有任何建议吗?有没有一种更简单的方法可以在不涉及使用 querySelector 的情况下做到这一点?我可能不想使用 dropzone 或类似的库/包,我只想学习如何做一个简单的上传文件。

如果有人对此有任何建议,我将不胜感激。我在这方面花了一些时间,我似乎在绕圈子。

编辑:根据下面第一条评论的建议,我添加了

for (var pair of data.entries()) {
  console.log(pair[0]+ ', ' + pair[1]);
}

到我的代码尝试和控制台记录我的数据值(即 dataForm 对象)。结果是:

file, [object File]

虽然这是真的,但它无助于解决我的问题。

【问题讨论】:

  • How to inspect FormData?的可能重复
  • 我已经尝试过该解决方案,但它没有按我的需要工作。我将编辑我的评论。

标签: html forms file reactjs file-upload


【解决方案1】:

将您的调用更改为以下方式,它应该可以工作(数据是您的 FormData):

axios.post('http://localhost:5000/upload',data,config) 

除此之外,由于您使用的是 React,而不是使用 querySelector,您可以使用文件输入中的 onChange 事件。 举个例子:

    import React,{Component} from 'react'
    class UploadComponent extends Component {
      constructor(props, context) {
        super(props, context);
        this.state = {file: null};

        this.handleFileChange = this.handleFileChange.bind(this);
        this.sendFile = this.sendFile.bind(this);
      }

       handleFileChange(event) {
          this.setState({file:event.target.files[0]})
        }

       sendFile() {
          //In here you can get the file using this.state.file and send
        }

      render() {
       return(
            <div>
              <input className="fileInput" type="file" onChange={this.handleFileChange}/>
              <button type="submit" onClick={this.sendFile}>Upload </button>

            </div>
       )
     }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2023-03-20
    • 1970-01-01
    • 2015-03-23
    • 2013-11-10
    • 2019-06-08
    • 2017-11-20
    相关资源
    最近更新 更多