0

我正在尝试通过 React 中的表单字段将图像发送到后端。我首先在我的构造函数类中将状态分配为空

this.state = {
  image: "",
}

然后,我为图像和普通文本字段创建了一个 handleChange 函数。

handleChange(event) {
  const state = this.state;
  switch (event.target.name) {
    case 'image':
      state.image = event.target.files[0];
      break;
    default:
      state[event.target.name] = event.target.value;
  }
  this.setState(state);
}

在 handleSubmit 函数中,我正在调用 FormData 函数并将图像附加到它,如下所示

handleSubmit(event) {
		event.preventDefault();
		const { syllabus,image } = this.state;
		let formData = new FormData();
		formData.append('image', image);
		axios.post('api', { syllabus, formData })
			.then((response) => {
				console.log(response);
			});
	}

最后,这是我的表单域

<span className="btn btn-default btn-file file-choose">
		<input type="file" name="image" placeholder="Enter Image" onChange={this.handleChange} />
													</span>

当我提交此表单并在 Chrome 控制台中检查我的“网络”选项卡时,formData 似乎为空,即没有传递图像。当我选择一个文件调用后端路由时,文件被上传,但我无法从 React 前端实现这一点,并且图像永远不会被传递。我哪里错了?

4

3 回答 3

0

您需要发送内容类型的标头

const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }

    return axios.post('api', { syllabus, formData }, config)
于 2018-04-04T10:04:20.887 回答
0

我自己解决了。首先我分配了一个默认状态this.state={image: new File([''], ''),}

这是它的处理函数

handleIChange() { const inputFile = $("input#input-image")[0].files[0]; this.setState({ image: inputFile }); }

这就是提交的方式

handleSubmit(event) {
  event.preventDefault();
  const image = this.state.image;
  let formData = new FormData();
  formData.append("image", $("input#input-image")[0].files[0]);
  //console.log("image3", $("input#input-image")[0].files[0])
  //console.log("Data", formData)
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data;boundary=${data._boundary}'
    }
  };
  axios.post('api', formData, config)
    .then((response) => {
      console.log(response);
      let id = response.data._id;
      this.props.history.push('route);
    });
}

于 2018-04-05T06:20:18.087 回答
0

在您的 HTML 中,您应该有

<form enctype="multipart/form-data">
   ...rest of your code
</form>

如果您想检查数据,请尝试使用

for (let obj of formData.entries()) {
   console.log(`${obj[0]} => ${obj[1]}`); 
}
于 2018-04-05T01:11:03.583 回答