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 <input type="file" onChange={this.handleChange} />
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
})
};
create a method in your Component that handles the submit, in the onSubmit
attribute of your form call it like: onSubmit="{this.handleSubmit}"
and post your data in an async way.
In your submitForm handler, pass a reference to the event and use event.preventDefault().
submitForm(event) {
event.preventDefault();
...other code here...
}
You can also try
<form className="upload-form" ref="uploadForm" id="uploadForm" action="http://localhost:3050/upload" method="POST" enctype="multipart/form-data" onSubmit={ (event) => { event.preventDefault(); } }>