Search code examples
javascriptreactjsant-design-proumijs

how to load images from a local directory and display them in reactjs app?


hello dear developers,

i'm using ant design app template as frontent and a graphql api serving as backend, i have reached a situation where i would like to fetch list of posts, everything is working fine on the backend, the API returns the posts along with their images path.
To understand more , images path are save on database, and the images itself are stored in local folder.

Now, i dont know how to load those images with paths i have retrieved when i fetched the posts.

i have tried google, but no similar situation, i've found an issue on gethub but it was talking about displaying a single image by using import image from folder and then put it inside img tag and that is not my case.

i know there is an alternative way which is to deploy my backend on a web server and then get direct like to the stored images but thats not ideal for me.

ps: " im a newbie"

Thank you all,


Solution

  • There are a couple of different approaches:

    1) Public folder

    When you start a react app, in your folder structure you'll find a "public" folder. This folder for example also contains the favicon. When you put your images there, you can reach them by

    <img src="/imagename.jpg" />
    

    In your database, you will need to store the path "/imagename.jpg" to reach them then.

    If you would create a subfolder in the "public" folder, the path in the src attribute will also need to change. Example: - public -- assets --- avatar.jpg

    <img src="/assets/avatar.jpg" />
    

    2) S3 (or some similar services)

    Upload them to Amazon S3 and store that path. This can either be done manually or let your API handle this. This way you can just provide an absolute path to the img-tag.

    3) Own webserver

    Upload them to your own webserver while you upload the image.

    Remark: Retrieving files from a local folder outside your project folder is not possible without the use of some other webserver.