Reputation: 117
Hey I am using react with a flask backend and I am trying to have a Form where users can upload images which should send to the backend and stored in database. So this is my approach but I am not sure which format is the best to store it in the db. And is FormData even a good solution?
// updates thumbnail in state when new file is selected
handleFileSelect = (event) => {
this.setState({
thumbnail: event.target.files[0],
});
};
// File Upload
handleFileUpload = (event) => {
const fd = new FormData();
fd.append("image", this.state.thumbnail, this.state.thumbnail);
axios.post("url", fd).then((res) => {
console.log(res);
});
};
Upvotes: 0
Views: 1157
Reputation: 4546
If axios
is the way your going, then i would recommend having a component that does the file upload functionality with an onChange
to listen to the event.target.files
and an input type of file
. Maybe even add in the accepted types through the html attribute accept
.
You can use FileReader
, allowing you to read the content of the files stored on the users computer (async). Using this as a separate function, you can use that FileReader
method to extract Base64
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
Fetching the form data:
const formData = new FormData();
formData.append('file', file);
Then your axios
would look something like this
axios({
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
data: dataForm,
url: 'urlhere',
onUploadProgress: (ev: ProgressEvent) => {
//Uploading progress functionality here....
},
})
.then((resp) => {
fetchBase64(file, (uri: string) => {
//maybe set a useState here for the Image URI or upload status.
});
})
.catch((err) => console.error(err));
Progress function:
const progressPercentage = Math.round(progressEvent.loaded / progressEvent.total * 100);
Upvotes: 1