1
votes

Please what I am getting wrong in my code? I want to setup my web app so that when users post image through a form with other text data, the image will be uploaded to cloudinary and the url will be returned and along with other data submitted by the user, all the record will be saved to my database. Please note that I am using pg-promise library and postgres DB. I include my codes below for reference.

MY DATA SCHEMA

CREATE TABLE photo_table (
  post_id uuid REFERENCES post(post_id) NOT NULL,
  photo_by text REFERENCES m_user(username),
  title text NOT NULL,
  description text NOT NULL,
  photo_url text NOT NULL,
  category text,
  location text,
  campaign text,
  posted_on timestamp NOT NULL default now(),
  updated_on timestamp NOT NULL default now(),
  PRIMARY KEY (pid)
);

MY CLOUDINARY & MULTER CONFIG FILE

const cloudinary = require('cloudinary').v2;
const multer = require("multer");
const cloudinaryStorage = require("multer-storage-cloudinary");

cloudinary.config({
  cloud_name: 'xxxxxxxx',
  api_key: 'xxxxxxxx3115',
  api_secret: 'xxxxxxxxxxxxYXpmAAr3b04'
}); 

const storage = cloudinaryStorage({
  cloudinary: cloudinary,
  folder: "photos",
  allowedFormats: ['jpg', 'jpeg', 'png'],
  transformation: [{ width: 960, height: 960, crop: "limit" }],
  filename: (req, file, callback) => {
    const name = file.originalname.split(' ').join('_');
    callback(undefined, name);
  }
});

module.exports = multer({storage: storage}).single('photo');

MY API POST REQUEST

const multer = require('../middlewares/multer/photo-config'); 

//multer is called in my route file as shown in the line below

router.post('/', multer, photoCtrl.addPhoto);

The function below is my controller request

function addPhoto(req, res, next) {
  const queryPhoto = 'INSERT INTO post (post_type, created_on) VALUES($1, $2) RETURNING pid'
  db.tx('my-transaction', t => {
    return t.one(queryPhoto, ['photo', 'now()'])
        .then(post => {
          const data = {
        photo_by: req.body.username,
        title: req.body.title,
        description: req.body.description,
        photo_url: req.files,
        category: req.body.category,
        location: req.body.location,
        campaign: req.body.campaign
      }
      const insertPhotoText = `INSERT INTO photo_table (pid, photo_by, title, description, photo_url, category, location, campaign, posted_on, updated_on) 
                                   VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`
      const insertPhotoValues = [post.pid, data.photo_by, data.title, data.description, data.photo_url, data.category, data.location, data.campaign, 'now()', 'now()']
              return t.none(insertPhotoText, insertPhotoValues);
        });
})
    .then(function () {
      res.status(200)
        .json({
          status: 'success',
          message: 'One photo added'
        });
    })
    .catch(function (err) {
      return next(err);
    })
  }
  
1
Thanks @aditi. Let me try this. But my main challenge is coming because I'm trying to send the post request in a transaction using pg-promise. - Jetro Olowole

1 Answers

2
votes

In order to upload to Cloudinary, you need to call the uploader() method: https://cloudinary.com/documentation/node_integration

Sample code:

app.post('/', upload.any([{ name: "test" }]), (req, res) => {
        var files=req.files;
        if(files){
            files.forEach(function(file){
                cloudinary.uploader.upload(file.path, function(result) { 
                console.log(result);
            });
            });
        }