'Multiple photo uploads from ReactJS
I am new to development. I have a C# WEB API backend. I have a functionality in the app where users can upload multiple pictures with comment.
How I am trying to save multiple photos is I am saving the first picture from the files array with one post request. Then I am saving the rest of the photos by comma-separated in the database table from the files array with a different post request. This way I can successfully save at most 2 pictures. The others never get saved in database table. Could you please point me out what I am doing wrong, or what modifications I must make? Here is my React Code:
(Today() method saves the first picture, then the tomorrow() method is called inside the today method to append the rest of the pictures).
const today = async (files,e) =>
{
e.preventDefault();
const formData = new FormData();
formData.append('UId', userId);
formData.append('UEmail', userEmail);
formData.append('FComment', comment);
formData.append('FImageFile', files[0]);
axios.post(Config.POST_COMMENT,formData) //Config.POST_COMMENT has the URL for api
.then( res => {
setComment("");
console.log(res.data.fId);
console.log(files.length);
if(files.length > 1)
{
console.log("image length 2");
for(let i = 1 ; i <files.length;i++)
{
console.log(`sending ${i} image`);
tomorrow(files[i],res.data.fId,e);
}
}
setLoading(true);
toast.success('Comment has been posted',{ //THE SUCCESS NOTIFICATION
position: toast.POSITION.TOP_RIGHT,
hideProgressBar: false,
autoClose: 2000,
});
})
.catch(err=> console.log(err.response))
}
const tomorrow = async (file,commentId,e) =>
{
e.preventDefault();
const formData = new FormData();
formData.append("FId", commentId);
formData.append('UId', userId);
formData.append('UEmail', userEmail);
formData.append('FComment', comment);
formData.append('FImageFile', file);
axios.post(Config.UPDATE_COMMENT_IMAGES,formData)
.then( res => {
setComment(""); // AFTER THE COMMENT IS POSTED THE COMMENT GET CLEARED FROM THE COMMENT BOX
document.getElementById('imageUploader').value = null; //THE CHOSEN IMAGE FILE NAME GET CLEARED AFTER COMMENT HAS BEEN POSTED
setCommentId(res.data.fId);
console.log("2nd image uploaded");
console.log(commentId);
setLoading(true);
})
.catch(err=> console.log(err.response))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
