I uploaded my image in this way and this method works, it uploads in a string:
const [image, setImage] = useState("");
//------------------^^^^^^^^^^^^^^^^-------------------------
const handleImage = (e) => {
console.log("Handle image called");
const selectedFile = e.target.files[0];
console.log("Selected file:", selectedFile);
if (selectedFile) {
const reader = new FileReader();
reader.onload = (e) => {
const imageData = e.target.result;
console.log("imageData: ", imageData);
setImage(imageData); // Store the Base64-encoded image data
};
reader.readAsDataURL(selectedFile);
}
};
And now in another file i have retrieved data from mongo which includes the image in what i think is base 64 and is a very long string. I am trying to render image like this but its not working only alt is showing:
const petCards = petData.map((pet, index) => (
<div className="card-results-find" key={index}>
<div className="img-card-find">
<Image
src={`data:image/jpeg;base64,${pet.image}`}
//I have also tried {petData.image} for src
alt={pet.catName}
layout="fill"
/>
</div>
//css:
.img-card-find {
position: relative;
width: 100%;
height: 90vh;
}
the petData.image include something like this:
image
EDIT
I uploaded the image like this:
const imageData = imageBase64.split(",")[1];
2
Answers
Change the way you send data to backend by just sending the url:
and in the server stop doing this:
const imageData = imageBase64.split(",")[1];
and encode the image:
const encodedImageData = encodeURIComponent(imageData);
this should store your image to db as a url
and when receiving the image:
this will do the job 🙂