【问题标题】:reactjs: Cannot pass file to node backend by reactreactjs:无法通过反应将文件传递到节点后端
【发布时间】:2018-09-13 20:18:52
【问题描述】:

我正在尝试通过 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 前端实现这一点,并且图像永远不会被传递。我哪里错了?

【问题讨论】:

    标签: javascript reactjs multer-s3


    【解决方案1】:

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

    const config = {
            headers: { 'content-type': 'multipart/form-data' }
        }
    
        return axios.post('api', { syllabus, formData }, config)
    

    【讨论】:

      【解决方案2】:

      在你的 HTML 中,你应该有

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

      如果您想检查数据,请尝试使用日志记录

      for (let obj of formData.entries()) {
         console.log(`${obj[0]} => ${obj[1]}`); 
      }
      

      【讨论】:

        【解决方案3】:

        我自己解决了。首先我分配了一个默认状态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);
            });
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-10-20
          • 1970-01-01
          • 2023-03-29
          • 2021-08-07
          • 2021-04-01
          • 1970-01-01
          • 2021-04-25
          相关资源
          最近更新 更多