'nodejs multer retrieve stored images to the client side

I have created file storage in nodejs application to store images in uploads folder. which works fine but now I want to display those images I have read some other posts but I am still quite unsure.

Here is my code:

 var Storage = multer.diskStorage({
 destination: function(req, file, callback) {
 var pathname = file.originalname;
 var path = pathname[0].replace('_','/');
 cb(null,'./uploads'+pathname);
 },
 filename: function(req, file, callback) {
 var pathname = file.originalname;
 var filename = pathname[1];
 if(pathname!=undefined)
 callback(null, pathname);
 }
 });
 var upload = multer({ storage: Storage }).single('file');

router.post('/upload', multer({dest:'./uploads/'}).single('file'), function(req,res)
 {
 return res.status(201).json({result:req.file});
 });

from console log I get

{ fieldname: 'file',
  originalname: '1569402978357.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: './uploads/',
  filename: 'ada9282345565e8a77c6adc4b2d15836',
  path: 'uploads\\ada9282345565e8a77c6adc4b2d15836',
  size: 170272 }

and in the uploads it is stored as filename

my problem is how can I display this image back? should call it from stored filename or should I change the storage to save it as original filename with file extension?



Solution 1:[1]

The choice to keep the original file name differs from use case to use case. In either case you will have to store the name somewhere in a persistence medium (like a database) so that while displaying it back you can look into your uploads directory and send the file back.

Solution 2:[2]

Depending on your use case, if you want to store the files in a different name, you need a way to find the files at a later stage. It can be achieved by storing the names in a database or you could even use some kind of formula to find out the file name of the stored file from the original one.

E.g:

name_of_stored_file =  md5(name_of_original_file)

As files (images) are now stored in your backend, you can expose some API to send the files to client on request. Again this completely depends on the use case, but here's a simple example of using Expressjs res.sendFile method:

app.get('/file/:fileName', function (req, res) {
    const filePath = // find out the filePath based on given fileName
    res.sendFile(filePath);
});

http://expressjs.com/en/api.html#res.sendFile

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikunj Jain
Solution 2 KruserG