Search code examples
javascriptnode.jscloudinary

How to upload an image to cloudinary


I want to upload an image to cloudinary form my NodeJS api, i have my model, in this model i have a field called image, this field is type string and here I want to save the url that a receive as response of cloudinary.

Here is my model.js

'use strict';

const mongoose = require('mongoose');

const CursoSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  image: {
    type: String,
  },
  description: {
    type: String,
    required: true
  }
});

module.exports = mongoose.model('Curso', CursoSchema);

And my controller.js, here is where I have to save the url, I tried with the method of cloudinary docs.

var imageFile = req.files.image;
cloudinary.uploader.upload(imageFile.path, function(result){
  if (result.url) { res.status(200).send({url: result.url});
  }else {
    console.log('Error uploading to cloudinary');
 }
});

but I just uploaded images. Here is my controller.js

'use strict';

const Curso = require('../models/curso');
const config = require('../config');
const cloudinary = require('cloudinary');

cloudinary.config({
  cloud_name: 'something',
  api_key: 'somthingelse',
  api_secret: 'andotherthing'
})

function saveCurso(req, res) {
  let curso = new Curso();
  let params = req.body;
  curso.name =  params.name;
  curso.description = params.description;
  //How to get the image and upload it to cloudinary

  curso.save((err, cursoSaved)=>{
    if(err){return res.status(500).send({message:'Error'});}
    if(!cursoSaved) return res.status(404).send({message: 'Empty'});
    return res.status(200).send({curso: cursoSaved});
  });
}

module.exports = {
  saveCurso,
}

And my routes.js file:

'use strict';

const express = require('express');
const api = express.Router();
const cursoController = require('../controllers/curso');

api.post('/curso', cursoController.saveCurso);

module.exports =  api;

I want to save the data with the name, description and in the image, i want to save the url from cloudinary.

I saved some images in cloudinary but I can't find the way to save only the url in my image field

NOTE: I'm using body-parser and this is my app.js

'use strict';

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

const curso_routes = require('./routes/curso');

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.use('/api', curso_routes);

module.exports = app;

Solution

  • First you need to handle the multipart/form-data using a package like multer or multiparty. So, using multiparty :

    'use strict';
    
    const Curso = require('../models/curso');
    const config = require('../config');
    const cloudinary = require('cloudinary');
    const multiparty = require('multiparty');
    
    cloudinary.config({
      cloud_name: 'something',
      api_key: 'somthingelse',
      api_secret: 'andotherthing'
    })
    
    function saveCurso(req, res) {
    
      //How to get the image and upload it to cloudinary
      let form = new multiparty.Form({ maxFilesSize: 10 * 1024 * 1024 }); //setting max size of image to 10MB
      form.parse(req, (err, fields, files) => {
        if (err) return err
        let curso = new Curso();
        curso.name = fields.name;
        curso.description = fields.description;
        cloudinary.v2.uploader.upload(files.content[0].path, (err, result) => { // content is the name of the image input on the front end form
          if (err) return err
          curso.image = result.secure_url;
          curso.save((err, cursoSaved) => {
            if (err) { return res.status(500).send({ message: 'Error' }); }
            if (!cursoSaved) return res.status(404).send({ message: 'Empty' });
            return res.status(200).send({ curso: cursoSaved });
          });
        });
      }) 
    }