node.jsexpresspdfcloudinary

How to upload a PDF Document on Cloudinary


I am trying to upload a PDF document on Cloudinary through a node.js server. The current approach I am using is inadequate and doesn't work. I will appreciate if anyone can proffer a solution to this problem that works, thank you.

Cloudinary Storage Configuration:

const cloudinary = require("cloudinary").v2,
  { CloudinaryStorage } = require("multer-storage-cloudinary");  

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});
 
const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  folder: "<some_folder>",
  allowedFormats: ["jpg", "png", "pdf"],
});


module.exports.store = storage;

Image Upload Route:

const express = require("express"),
  router = express.Router(),
  cors = require("cors"),
  fileUploadController = require("../../../controllers/haulage/users/fileUploadController");

const authenticate = require("../../../auth/auth"),
  multer = require("multer"),
  storage = require("../../../../config/cloudinary").store,
  parser = multer({ storage: storage });

router
  .route("/images")
  .put(
    authenticate,
    cors(),
    parser.array("image"),
    fileUploadController.uploadImage
  );

module.exports = router;

Image Upload Controller:

exports.uploadImage = async (req, res) => {
  try {
    const events = JSON.parse(JSON.stringify(req.files));

    const urls = [];    

    events.map((e) => {
      const url = e.path;
     
      urls.push(url);
    });

    res.status(201).json({ URLS: urls });
  } catch {
    res.status(500).json({ error: "Server Error, Image Failed to Add" });
  }
};


Solution

  • Are you part of the free plan in Cloudinary? If yes, it might be related to this issue: https://support.cloudinary.com/hc/en-us/articles/360016480179-Why-does-my-pdf-link-isn-t-working- If not, can you please elaborate on the issue? where do you see the error? The code to upload pdf ( same as any image):

    var cloudinary = require('cloudinary')
    cloudinary.v2.uploader.upload("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",function(res,err){console.log(res,err)});