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.
- Possible duplicate of Ajax post a file from a form with AxiosTholle– Tholle2018-08-07 04:18:28 +00:00Commented 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.Sajad Beheshti– Sajad Beheshti2018-08-07 05:02:51 +00:00Commented Aug 7, 2018 at 5:02
Add a comment |
1 Answer
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.
1 Comment
Sajad Beheshti
Thanks, but i have problem with get data from input and put in state. can you help me?