I want to add picture files with Dropzone and show preview on browser.
So, I have to get src
which can use at <img />
. So I do this process:
const handleAddImages = async (inputImages: any[]): Promise<void> => {
const imagesWithSrc = inputImages.map((img) => {
const reader = new FileReader();
new Promise((resolve, reject) => {
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(img);
}).then(() => (img.src = reader.result));
return img;
});
const nextImages = [...currentImages, ...imagesWithSrc];
handleOnChange({
//set state
target: {
name: "images",
value: nextImages,
},
});
};
And show the images in this component:
export const FileList = ({
images
}: any) => {
const imgs: any[] = images;
return (
<Wrapper>
{imgs.map((img, index) => (
<ImgBox key={index}>
<img src={img.src} />
</ImgBox>
))}
</Wrapper>
);
};
I have an images array imgs
and contains image file objects.
When I do this:
console.log(imgs[0]);
it will output every attributes in image file object of index 0 including the image source src
in base64 from filereader API.
but when I do this:
console.log(imgs[0].src);
it will output undefined
,
even I do console.log in map like this:
imgs.map((img, index) => {
console.log(img);
console.log(img.src);
})
and get the same result, what is the problem?
console.log("imgs[0]", imgs[0]);
console.log("imgs[0].src", imgs[0].src);
ouput:
By the way, I can get the size attribute by imgs[0].size
at first,
and get the imgs[0].src
after add another picture.