skip to Main Content

I used multer to download the image and save the path of the image to the database, and then how can I get the image from the client and show it on the screen?

import multer from 'multer';

const storageConfig = multer.diskStorage({
    destination: (req, file, cb) => {
         cb(null, './images')
    },

    filename: (req, file, cb) => {
          cb(null, Date.now() + '-' +  file.originalname)
    }
})

const upload = multer({storage: storageConfig});

 let path = '';

app.post('/upload',upload.single('image'), (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    if(req.file) {
        console.log(req.file);
        path = req.file.path;
        res.send('hi')
        return;
    }
    res.send('bye')
})

after I received the file path I saved it in the database, but I don’t know how to use it later to show this picture on the screen

2

Answers


  1. As per your code mention, you can show the image in react as below.

    <img src={`${backend_url}/${path_you_get_from_database}`} />
    

    In your case backend_url is http://localhost:3000

    Login or Signup to reply.
  2. After saving the path of the file to the database, you need to implement a route to fetch the image url. Then you can simply use it in your client application. Here I’m expecting you are only fetching a single image using the id. If you want to fetch all the urls stored in db, kindly make necessary changes to this code.

    Eg:

    Server.js

    app.get('/image/:id', async (req, res) => {
      //Assuming you have a db connection pool and you are using postgres
      const client = await pool.connect();
      const { id } = req.params;
      const query = 'SELECT url from imag_collection WHERE id = $1';
      const result = await client.query(query, [id]);
      if (!result.rowCount) {
        // Your error handling logic
        // or simply
        res.status(404).json({ message: 'No image found using the given id' });
      }
      res.status(200).json({url: result.rows[0].url});
    });
    

    Client (ReactJS)

    // Collect id from user
    
    const result = await fetch(`${serverUrl}/image/${id}`);
        
    if(!result.ok) {
      // Handle the error here
    }
        
    <img src={`${result.url}`} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search