Add images to mongodb via api using Postman

Asked

Viewed 309 times

0

Good morning, I’m building an api on nodejs to access mongodb. I want to add images in this database and return the path of this image to my android application. I want to store the images directly in the bank or using Postman. Does anyone have any idea how I add the images in mongodb?

Here is the current code.

medicoRouter.post('/medicos', (req, res, next)=>{


    async function salvaMedico(){
        const medicos = new Medicos({
            nome: req.body.nome,
            formacao: req.body.formacao,
            crm: req.body.crm,
            cidade: req.body.cidade,
            //caminho_foto: url_imagem,
            //data_atualizacao: null
            });


        try{
            const result = await medicos.save();
            console.log("Operação realizada com sucesso");
            res.status(201).send({ message: "Cadastrado com sucesso!"});
            /* res.statusCode = 201;
            res.send(); */
        } catch(erro){
            console.log(erro.message);
            res.status(406).send({ message: "Cadastro falhou"});
            /* res.statusCode = 406;
            res.send(); */
        }
    }

    salvaMedico();
});

1 answer

0


I believe you will need to use a dependency called "multer" to work with Multipart/form-data sending. To install, simply:

npm install --save multer

Multer adds an object body and an object file to the object request. That is, you can access the req.body and the req.file in your code.

Of multer documentation, a basic use would be:

var express = require('express');
var multer  = require('multer');
var upload = multer({ dest: 'uploads/' }) //caminho que o arquivo ira percorrer

var app = express();

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file é o arquivo avatar que vem do form <input type="file" name="avatar" />
  // req.body os campos de texto se houver algum
})

In your case, a way to store the file path in mongodb can be done as follows:

const multer = require('multer');
const upload = multer({
      dest: 'seu/caminho/para/upload',
      storage: multer.diskStorage({ //aqui irá gerenciar o armazenamento no disco
         destination: (req, file, cb) => {
             cb(null, './seu/caminho/para/salvar');
         }
      });
});

medicoRouter.post('/medicos', upload.single('nomeCampoForm'), (req, res, next)=>{ 
//fazendo upload de um único arquivo de cada vez usando o método single()

    async function salvaMedico(){
        const medicos = new Medicos({
            nome: req.body.nome,
            formacao: req.body.formacao,
            crm: req.body.crm,
            cidade: req.body.cidade,
            caminho_foto: req.file.path, //alteração aqui 
            //data_atualizacao: null
            });

            //req.file.path irá buscar dentro do objeto file, o caminho especificado
       [...]
    salvaMedico();
});

I believe this will solve your problem at first. I advise you to read more about the multer documentation, is very intuitive and has many more things that can help you when dealing with file uploads. For example, set the file types the upload accepts (Mime types).

Don’t forget to add enctype="multipart/form-data" in your form or set this in Postman.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.