Search code examples
reactjsformsfile-uploadonchange

How to take value from onChange to Upload Image in React


Hello guys I got the following 2 functions:

 changeProfileImage=(event)=>{
       
      this.setState({file:event.target.files[0]});
      
      
  }

and the upload one:

 upload(file) {
   
    let formData = new FormData();
    const username1 = localStorage.getItem('username')
    formData.append("file", file);
    return axios({
      method: 'post',
      url: 'http://localhost:3000/users/addUserImage/'+username1,
      data: formData,
      headers: {
          'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
      },
  });
  }

Main scope is to update the username1 image with the given one from changeProfileImage function. How can I make my Upload function taking the setState file ?


Solution

  • You can pass the file value as an argument to the upload function when you call it. code pen: https://codepen.io/akartit/pen/PoaXgQO

    class App extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          file: null
        };
    
        this.changeProfileImage = this.changeProfileImage.bind(this);
        this.upload = this.upload.bind(this);
      }
    
      changeProfileImage = (event) => {
        // Set the file value in the state
        this.setState({ file: event.target.files[0] });
      };
    
      upload = (file) => {
        let formData = new FormData();
        const username1 = localStorage.getItem("username");
        formData.append("file", file);
        return axios({
          method: "post",
          url: "https://webhook.site/c62f75b5-32be-4f3f-a6cd-e84f515706f4",
          data: formData,
          headers: {
            "Content-Type": `multipart/form-data; boundary=${formData._boundary}`
          }
        });
      };
    
      render() {
        return (
          <div>
            <input type="file" onChange={this.changeProfileImage} />
            <button onClick={() => this.upload(this.state.file)}>Upload</button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));