react js handling file upload

后端 未结 7 924
长发绾君心
长发绾君心 2020-12-09 11:29

I\'m new to react js. I want to upload image asynchronously with react js Suppose I have this code

var FormBox = React.createClass({
  getInitialState: funct         


        
相关标签:
7条回答
  • 2020-12-09 12:10
    import axios from 'axios';
    var FormBox = React.createClass({
      getInitialState: function () {
        return {
          photo: [],
          name : '',
          documents:[]
        }
      },
      pressButton: function () {
        var component = this
        var data = new FormData();
        data.append("photo", component.state.photo, component.state.name);
        var request = axios.post('http://localhost:3000/document', data)
            request.then(function(response){
        // you need to send data from server in response
              if(response.status == 200){
                 console.log('saved in db')
                 component.state.documents.push(response.data.documents)
                 // pushed document data in documents array
               }
            })
    
    
      },
      getPhoto: function () {
        var uploadfile = document.getElementById(upload_doc).files[0]
        this.setState({
          photo: uploadfile, name : uploadfile.name
        })
      },
      render: function () {
        var documents = this.state.documents.map((doc)=>{
           return <div>
                    <a href={doc.url}>{doc.name}</a>
                    <img src={doc.photo} />
                  </div>
        })
       // you can show your documents uploaded this way using map function
        return (
          <form action='.' enctype="multipart/form-data">
            <input type='file' id='upload_doc'  onChange={this.getPhoto}/>
            <button onClick={this.pressButton}> Get it </button>
            <span>{documents}</span>
            // this way you can see uploaded documents
          </form>
        )
      }
    })
    
    ReactDOM.render(<FormBox />, document.getElementById('root'))
    
    0 讨论(0)
提交回复
热议问题