0

How can i get data from input with type file and send it with axios in reactjs? I found something about formData but i didn't find anything about get data from input and send it with axios. thanks.

2
  • Possible duplicate of Ajax post a file from a form with Axios Commented Aug 7, 2018 at 4:18
  • @Tholle I used this way and now i get error in server side, i uploaded 1 file but in Django administration there are about 5 or 6 media in media field. Commented Aug 7, 2018 at 5:02

1 Answer 1

1

Lets assume that you have all the input data along with the file in your state like

constructor(props) {
    super(props);
    this.state = {
        file : someName.txt,  // file input
        stateName : 'MP'      // Text Input
        date : 07/08/2018     // Date input
    }
}

Now, in you handelSubmit method construct a JSON Object

handelSubmit = () => {
    const { file, stateName, date } = this.state;
    let data = [];
    data['file'] = file;
    data['stateName'] = stateName;
    data['date'] = date;

    // a function which makes a axios call to API.
    uploadFile(data, (response) => {
        // your code after API response
    }); 
} 

Here is a function to make a API call by axios

uploadFile(data, callback) {
    const url = '';         // url to make a request
    const request = axios.post(url, data);
    request.then((response) => callback(response));
    request.catch((err) => callback(err.response));
}

UPDATED :

Text On Change method to set state

handelOnChange = (event) => {
    const target = event.target;
    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
}

Method on upload of file to set into state

handelOnUploadFile = (event) => {
    this.setState({
      file : event.target.files
    })
}

Here is a JSX code.

render() {
    return(
        <div>
            <input type="file" onChange={this.handelOnUploadFile} />  {/* input tag which to upload file */}
            <input type="text" name="stateName" onChange={this.handelOnChange} />  {/* text input tag */}
            <button type="submit" onClick={this.handelSubmit}> UPLOAD </button>
        </div>
    )
}

Hope it helps you.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but i have problem with get data from input and put in state. can you help me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.