1

Looking for help on Uploading and Retrieving Images from MongoDb using multer.

My front end is ReactNative.(Not sure if this is needed but just to be sure.)

Multer

Problem: After looking and following tutorials i'm able to encode my path to base64 and upload it to my DB but now i'm confused how to retrieve the file from my DB. I saw some tutorials about decoding it from base64 but I don't quite understand how do I go about retrieving an image and displaying it in postman. (I tried looking but haven't found anything that gives me an answer. I'm sorry if this is a duplicated question. If you could point me in a direction or give me some advice I would be really greatful.)

**POST**
route.post("/sad", upload.single("image"), (req, res, next) => {
  console.log(req.file);

  const img = fs.readFileSync(req.file.path);
  const img_enc = img.toString('base64');
  const obj = {
    usrImage: {
      data: new Buffer.from(img_enc, 'base64'),
      contentType: "image/jpg",
    },
  };
  console.log(obj);
  const newAccout = new account(obj);
  newAccout.save();
});


**RETRIEVE**
route.get('/sad',(req,res)=>{
     img.find({}).then((img)=>{
       res.json(img)      
//How do decode my buffer to show an image in Postman?
})
}
)

I am trying to create a userprofile where a username,password and image is saved. If you can help save an Image and then retrieve it from my accounts collection.

  • Just a wild guess: I think you should not wrap the IMG data with a JSON object if you want to display it. You should pass some content type header (image/jpg) and change the response tab to preview in postman. – bastianowicz Oct 30 '20 at 18:08
  • Thank you for the response. Can you expand on how do I pass a content type header? – Maahase Singh Oct 30 '20 at 18:10
  • https://nodejs.org/api/http.html#http_response_setheader_name_value Here is the corresponding place in the docs. Content type headers are used to tell the client how to render the data. – bastianowicz Oct 30 '20 at 18:13

3 Answers3

0

Hey I would advise that you start using a 3rd party for file upload like cloudinary very good way of managing files i.e images or video...

I am not that well of with multer but I can give a quick code example using Formidable does the same work as multer

Before you can start you'd need to make an account on cloudinary.com(don't worry its free)

Code below is how you could handle file upload

const Formidable = require("formidable"); //Meant for body parsing
const cloudinary = require("cloudinary").v2; // file uploader

//This below is your connection/configuration to get access to your cloudinary account so cloud_name, api_key and api_secret you'll get in your home dashboard(Cloudinary)

cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.API_KEY,
  api_secret: process.env.API_SECRET,
});

router.post('/api/file-upload', (req, res)=>{
    const form = new Formidable.InconmingForm();
    form.parse(req, (error, fields, files)=>{
        const {file} = files

        cloudinary.uploader.upload(file.path, {folder:"/"}, (err, res)=>{
        const file_url = res.secure_url //This would be the url for your file given back by cloudinary
        })
    })
})

This script should upload your file and the file_url will be having the url of the file that you upload having ssl then after that you can now continue saving to mongoDB

Cloudinary docs for NodeJS https://cloudinary.com/documentation/node_integration

Nice clear and understandable docs

Shameless plug

If you get lost you can check this video out on YouTube that I made handling file upload with cloudinary then save url given back to mongoDB

https://youtu.be/mlu-tbr2uUk

  • Thanks for the reply. Sorry but this isn't what I want but I did watch your videos I'll sub if I ever need to use cloudinary. – Maahase Singh Oct 31 '20 at 01:56
0

First call api find one

you will need fs module to complete following query

const fs = require('fs');

let data = await db.user.findOne({
    where: {
        id = req.body.id
    }
})
                         //   _________________ base 64 string data from findone query data
                         //  |
let buff = new Buffer(data.image, 'base64');

let name = name.jpeg
let path = `tmp/${name}`; // <--- destination and file name you want to give to your file

fs.writeFileSync(path, buff);// < --this will write file to given path

fs.readFile(path, function (err, content) {//  <------to send file in postman response
    if (err) {
        res.writeHead(400)
        console.log(err);
        res.end("No such image");
    } else {
         //specify the content type in the response will be an image
        res.writeHead(200);
        res.end(content);
    }
});

fs.unlink(path, (err) => { //  <-----to delete file from tmp directory
    if (err) {
        console.log(err)
    }
})

Aryan
  • 3,338
  • 4
  • 18
  • 43
-1

Try this and switch to preview tab in postman. I haven't tried it but maybe it helps.

route.get('/sad',(req,res)=>{
     img.find({}).then((img)=>{
          res.setHeader('contentType','image/jpg').send(img)      
      })
})
bastianowicz
  • 358
  • 2
  • 9
  • I tried this way and i'm only retrieving the data in the preview tab. It doesn't respond with an image. – Maahase Singh Oct 31 '20 at 02:00
  • Maybe send `img.data`. I am really guessing here. What do you mean by "retrieving the data"? – bastianowicz Oct 31 '20 at 05:37
  • When i use your code snippet to get the image file from my Db Collection it responds with : ` {"usrImage":{"data":{"type":"Buffer","data":[255,216,255,224,0,16,74,70,73,70, ....` It also shows said data in the preview tab instead of an image. – Maahase Singh Oct 31 '20 at 06:34
  • I think you have to read the buffer like you did in your post function. I haven't done sth like that so maybe look up how to use Buffer.from and load the data from your database the way you saved it there. – bastianowicz Oct 31 '20 at 06:55
  • Sorry it seems i'm still lost. Do you know any good tutorials of uploading images to MongoDb and retrieving said image? – Maahase Singh Nov 01 '20 at 03:41
  • https://stackoverflow.com/q/5823722/1063714 Have a look here. I am trying to test it later and provide a working example – bastianowicz Nov 01 '20 at 10:06