如何使用FormData在React.js中上传文件onSubmit?

时间:2017-11-02 12:38:08

标签: javascript reactjs express

我是React.js的新手并尝试通过表单将图片发送到我的数据库。我在后端有Express.js,在前端有React.js。这是我在React.js中的App.js。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LearningFirstComp from './components/LearningFirstComp';

class App extends Component {
 constructor(props) {
  super(props);
  this.state={
    inputTopValue:'',
    inputBottomValue:'',
    inputImageValue: '',
  }
  this.handleTopChange = this.handleTopChange.bind(this);
  this.handleBottomChange = this.handleBottomChange.bind(this);
  this.handleImageChange = this.handleImageChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}

  handleTopChange(event) {
    this.setState({inputTopValue: event.target.value});
    console.log("changing")
}

 handleBottomChange(event) {
    this.setState({inputBottomValue: event.target.value});
    console.log("descr")
}

handleImageChange(event) {
  this.setState({inputImageValue: event.target.value});
  console.log("imagechanged")
}

handleSubmit(event) {
    event.preventDefault();
    var mycoolform = new FormData();

    mycoolform.append('topstuff', event.target.topstuff.value);
    mycoolform.append('bottomstuff', event.target.bottomstuff.value);
    mycoolform.append('pic1', event.target.myimage.value)
    console.log(mycoolform)

    fetch('api/learning', {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Accept': 'application/json'
        },
        body: mycoolform
    })
    console.log(mycoolform,"this is the body")
    }



render() {
  return (
  <div className="App">
    <form onSubmit={this.handleSubmit} encType="multipart/form-data">
      <input type="text" name="topstuff" placeholder="title" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
      <input type="text" name="bottomstuff" placeholder="body" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
      <input type="file" name="myimage" onChange={this.handleImageChange} value={this.state.inputImageValue} /><br/>
      <input type="submit" value="yeah boy" />
    </form>
  </div>
    );
   }
  }

export default App;

我有控制台记录了&#34; mycoolform&#34;我提交后,在多个地方变量,所有返回为空。我没有正确创建formData或附加值吗? 而且,我的标题看起来可以将文件和文本发送到数据库吗?

0 个答案:

没有答案