Sajad Beheshti
Sajad Beheshti

Reputation: 689

Upload and send data with axios in reactjs

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.

Upvotes: 0

Views: 3830

Answers (1)

Naveen Heroorkar
Naveen Heroorkar

Reputation: 89

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.

Upvotes: 1

Related Questions