Reputation: 782
So I have this scenario where I am uploading the images. On front end, its React Js
and back end in Node Js
. Images get uploaded fine but when I have to display them on front end it doesn't work.
I am using react-image-gallery to display images like this:
<ImageGallery
items={this.state.currentImages}
lazyLoad={true}
ref={this.myRef}
showIndex={true}
/>
This is what is there in this.state.currentImages
:
[
{
"original": "/var/www/html/ciaoOrderTaking/projects/ciao_full_stack/uploads/images/items/IMAGE-1645782694696.jpg",
"thumbnail": "/var/www/html/ciaoOrderTaking/projects/ciao_full_stack/uploads/images/items/IMAGE-1645782694696.jpg"
}
]
In the browser the path becomes:
http://localhost:3000/var/www/html/ciaoOrderTaking/projects/ciao_full_stack/uploads/images/items/IMAGE-1645782694696.jpg
How can I make it work? Any solutions?
Upvotes: 0
Views: 1131
Reputation: 782
Turns out, this was the answer.
https://expressjs.com/en/starter/static-files.html
Upvotes: 0
Reputation: 492
You have to make URL and serve your uploaded files statically in the backend e.g., your backend port is 3000 and you have served statically uploads folder on nodejs backend. Upload folder structure: Uploads -> Images -> items -> IMAGE-1645782694696.jpg Now your file URL will become: http://localhost:3000/images/items/IMAGE-1645782694696.jpg
So make an function in the frontend which will convert your image url into accessible File URL like:
const toAbsoluteURL=(url)=>{
return `http://localhost:3000/${url}` // note that this is backend url
}
And map the function to array of images.
images=images.map((url)=>toAbsoluteURL(url?.original)); // now images array have accessible file urls
You can make accessible URL's with the above function as you want.
Upvotes: 1