'Adding image in the same Array React
Hello I'm having a problem in uploading additional product image in my array. The URL is duplicated when I uploaded 2 files. The result will be like this.
{
"url": "https://localhost:8000/1650517557416.jpg,https://localhost:8000/1650517559319.png",
}, {
"url": "https://localhost:8000/1650517557416.jpg,https://localhost:8000/1650517559319.png",
}
Here is my frontend
export const addAdditionalProductPictures = async (images, productId, url) => {
const ls = new SecureLS({ encodingType: "aes" });
const token = ls.get("token");
const formdata = new FormData();
for (let index = 0; index < images.length; index++) {
formdata.append("file", images[index]);
}
formdata.append("url", url);
return await fetch(`${API}/product/image/${productId}`, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
body: formdata,
})
.then((response) => {
return response;
})
.catch((err) => {
//console.log(err)
return err;
});
};
Here is my backend
exports.addImage = (req, res) => {
const { url } = req.body
let newImages = req.files.map(function (obj) {
const id = mongoose.Types.ObjectId();
return ({
url: url,
});
});
Product.findByIdAndUpdate(req.params.id, { $addToSet: { images: newImages }} , { new: true
}, (err, product)=> {
if (err) {
return res.status(400).json({
error: dbErrorHandler(err)
});
}
res.json(product);
});
}
And here is my implementation on frontend
<Button
autoFocus
color="inherit"
type="submit"
disabled={isSubmitting}
onClick={async () => {
setIsSubmitting(true);
let filesUrls = [];
for (var i = 0; i < selectedImageFiles.length; i++) {
const urlLink = await generateUploadUrl(
selectedImageFiles[i].type
);
const to_base64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
});
let blob = await to_base64(selectedImageFiles[i]);
let binary = atob(blob.split(",")[1]);
let array = [];
for (var x = 0; x < binary.length; x++) {
array.push(binary.charCodeAt(x));
}
let blobData = new Blob([new Uint8Array(array)], {
type: selectedImageFiles[i].type,
});
const uploadImageLink = await
uploadImage(urlLink,blobData);
const newUploadImageLink = uploadImageLink.url.split("?")
[0];
filesUrls.push(newUploadImageLink);
}
addAdditionalProductPictures(
selectedImageFiles,
product?._id,
filesUrls
)
.then((response) => {
if (response.status === 200) {
response?.json().then((e) => {
setIsSubmitting(false);
});
} else {
response?.json().then((e) => {
setIsSubmitting(false);
});
}
})
.catch((e) => console.log(e));
}}
>
I cannot get the URL from the AWS in the console in the backend. it returns me undefined. What is missing or what is wrong in my code?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
