I\'m setting up a file uploading functionality for the first time. I have a react front-end and an express server that will store the files. I have it set up so a user can submi
Here is how I handle submitting files with Axios
handleChange = ( event ) => {
const fileReader = new FileReader();
const fileToUpload = event.target.files[0];
fileReader.onload = ( upload ) => {
const allFiles = [ ...this.state.allFiles ].concat( upload.target.result );
this.setState({
allFiles
});
};
fileReader.readAsDataURL(fileToUpload);
};
The handleChange method is tied to the onChange event of the
Then in the form submit handler
handleSubmit = ( event ) => {
event.preventDefault(); //So the page does not refresh
const { allFiles } = this.state;
const Promises = [];
allFiles.forEach( file => {
Promises.push( Axios({
url: "a url goes here",
method: "POST",
data: {
file: file, //This is a data url version of the file
}
}));
});
Axios.all(Promises).then( result => {
alert(result.message); //Display if it uploaded correctly
})
};