Search code examples
reactjsfilefile-uploadimage-uploadreact-image

How can I call image from outer folder of my react-app folder in react.js


My image is stored in the server folder and my react app folder is food

enter image description here

I wanted to call images from server(server>uploads>foods) folder to food(food>src>home). I was used back path like as (../) but it doesn't work.

So, how I can call images from the server folder to the food folder in react

How can I call image from outer folder of my react-app folder in react.js


Solution

  • I assume, you have to fetch image from server folder, which is your express.js application.

    The images, CSS files, JavaScript files, and other files that the client downloads from the server are known as static files. These static files can be fetched with the use of the express framework and without the use of it.

    you may have following directory tree:

    server.js
    package.json
    package-lock.json
    nodemodules
      | -- *
    uploads
       -food
         | -- demoImage.png
    public
      | -- index.html
    

    Using the Express framework: Using the express framework its built-in middleware function express.static() can be used to serve static files.

    Filename: server.js

    // Requiring module
    const express = require('express');
     
    // Creating express object
    const app = express();
     
    // Defining port number
    const PORT = 3000;                 
     
    // Function to serve all static files
    // inside public directory.
    app.use(express.static('public')); 
    app.use('/images', express.static('images'));
     
    // Server setup
    app.listen(PORT, () => {
      console.log(`Running server on PORT ${PORT}...`);
    })
    

    Steps to run the program:

    1. Install express:
    npm install express
    
    1. Run the server.js file using the following command:
    node server.js
    

    Now you can access image from following url:

    http://localhost:3000/images/demoImage.png