以反应形式上传文件

时间:2018-11-22 00:21:22

标签: javascript reactjs forms api file

我想通过获取api上传文件。但是,我的formData()返回空。

var formData = new FormData();
data.append("file", file[0]);

const options = {
    method: 'POST',
    headers: {...},
    body: formData
}

fetch("url", options)
    .then(resp => resp.json())
    .then(result => ... );

有我的表格:

<form onSubmit={this.handleSubmit()}>
    upload file
    <button type="submit"></button>
</form> 

3 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是:

formData.set('file', file[0])

答案 1 :(得分:0)

您可以在formData内部看到的方式是这样的:

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

您可以尝试:

var formData = new FormData();

for (var key in files) {
  formData.append("file", file[0]);
}

这是我之前在React.Component类中编写的两个函数:

var formData = new FormData();

handleFileUpload = files => {
  var chosenData = new FormData();
  var allFiles = [];
  for (var key in files) {
    if (!isNaN(key)) {
      chosenData.append("document", files[key].name);
    }
  }
  for (var pair of chosenData.entries()) {
    allFiles.push(pair[1]);
  }
  this.setState({ chosenFiles: allFiles });
  for (var obj in files) {
    if (!isNaN(obj)) {
      formData.append("document", files[obj]);
    }
  }
};

buttonClicked = e => {
  e.preventDefault();
  var newData = [];
  var newFormData = new FormData();
  if (
    this.state.chosenFiles.length !== formData.getAll("document").length
  ) {
    newData = formData
      .getAll("document")
      .slice(-this.state.chosenFiles.length);
    for (var obj = 0; obj < newData.length; obj++) {
      newFormData.append("document", newData[obj]);
    }
    this.fileUploader(newFormData);
  } else {
    this.fileUploader(formData);
  }
};

在我的渲染器中:

<div id="selectFiles">
<label id="docFileLabel" htmlFor="docFile">
    Upload
  </label>
  <input
    type="file"
    id="docFile"
    className="docFile"
    onChange={e => {
      this.handleFileUpload(e.target.files, e);
    }}
    multiple
  />
</div>

示例图片:

enter image description here

另一个示例图片:

enter image description here

答案 2 :(得分:0)

data.append(“ file”,file [0]);应该是 formData.append(“ file”,file [0]);