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.
            Asked
            
        
        
            Active
            
        
            Viewed 3,740 times
        
    0
            
            
        - 
                    Possible duplicate of [Ajax post a file from a form with Axios](https://stackoverflow.com/questions/43013858/ajax-post-a-file-from-a-form-with-axios) – Tholle Aug 07 '18 at 04: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. – Sajad Beheshti Aug 07 '18 at 05:02
1 Answers
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.
 
    
    
        Naveen Heroorkar
        
- 89
- 8
- 
                    Thanks, but i have problem with get data from input and put in state. can you help me? – Sajad Beheshti Aug 07 '18 at 05:00
