I'm trying to load images from API to my client app. My first idea (which maybe is entirely wrong) is to save pictures on a folder and store a path to an image in the database, instead of storing an image inside a db. The problem is with with retrieving and displaying an image.
My first attempt was looking like this:
<Card.Img variant="top" src={props.postPic} />
where props.postPic
woud look like this: C:\Users\Admin\Desktop\img.jpg
. But React can't seem to find it. Then I created the folder inside a src folder.
Hardcoding the path seems to work:
<Card.Img variant="top" src={require('../../../../Images/post_pics/' "256546654_2093222944148704_432196633022662491_n.jpg")} />
However, when I tried to pass it as a parameter:
<Card.Img variant="top" src={require('../../../../Images/post_pics/' props.imagePath ".jpg")} />
where props.imagePath
is now just an image name, the console in browser says Uncaught (in promise) Error: Cannot find module './0347008d-1f7c-47da-8bc5-a740374b4208.jpg'
.
I also tried string interpolation:
<Card.Img variant="top" src={require(`../../../../Images/post_pics/${props.imagePath}.jpg`)} />
Which gives the same result. Can I somehow achieve with the way am doing it (storing path to image in DB or name of the image) or do I have to change the implementation? If so, what is the proper way of handling images in database?
CodePudding user response:
Okay, I will share what I could find.
I haven't managed to set local paths to React, this either seems a bad approach, or it's simply impossible. Instead, I changed the way of handling photos in my API. I send them to the API, convert them to Base64 stringand store them inside the database. Then, when I send base64 from database to React component, I load it like this:
src={`data:image/jpeg;base64,${this.props.imagePath}`}
where imagePath
is base64 string.
CodePudding user response:
In real life applications, images are stored in cloud like in S3, or digitalocean spaces. and the link of the image which is stored in cloud is saved in database.
But in your scenario you are not uploading it to aany clou provider. And as you are using your local Images stored in your project directory you can import them and then use them.