Maahase Singh
Maahase Singh

Reputation: 33

nodejs: Retrieving base64 Images from Mongodb using Postman

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.

Upvotes: 1

Views: 1332

Answers (3)

Aryan
Aryan

Reputation: 3636

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)
    }
})

Upvotes: 0

bastianowicz
bastianowicz

Reputation: 484

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)      
      })
})

Upvotes: -1

Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

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

Upvotes: 0

Related Questions