Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't upload an image using ESM for cloudinary

I have a problem in this part of my code,with COMMONJS and it's working, my question is how can I make it work on ESM, I've tried this but not workiing :

import express from 'express';
const router = express.Router();
import cloudinary from 'cloudinary';
import { unlinkSync } from 'node:fs'; 
 const router = require('express').Router();
const cloudinary = require('cloudinary');
const { unlinkSync } = require('node:fs');

// we will upload image on cloudinary
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

// Upload image only admin can use
router.post('/upload',  (req, res) => {
    try {

        cloudinary.v2.uploader.upload(file.tempFilePath, { folder: 'test' }, async (err, result) => {
            if (err) throw err;
            removeTmp(file.tempFilePath);

            res.json({ public_id: result.public_id, url: result.secure_url });
        });
    } catch (err) {
        return res.status(500).json({ msg: err.message });
    }
});

const removeTmp = (path) => {
        unlinkSync(path, err => {
            if(err) console.log('this is the error',err);;
        });
        console.log(`successfully deleted ${path}`);

};
module.exports = router; 
like image 855
Ronice Yemeli Avatar asked Dec 06 '25 10:12

Ronice Yemeli


2 Answers

Try this one :

import express from 'express';
import multer from 'multer';
import { v2 as cloudinary } from 'cloudinary';
import streamifier from 'streamifier';
import { isAdmin, isAuth } from '../utils.js';

const upload = multer();

const uploadRouter = express.Router();

uploadRouter.post(
  '/',
  isAuth,
  isAdmin,
  upload.single('file'),
  async (req, res) => {
  
    cloudinary.config({
      cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
      api_key: process.env.CLOUDINARY_API_KEY,
      api_secret: process.env.CLOUDINARY_API_SECRET,
    });
    const streamUpload = (req) => {
      return new Promise((resolve, reject) => {
        const stream = cloudinary.uploader.upload_stream((error, result) => {
          if (result) {
            resolve(result);
          } else {
            reject(error);
          }
        });
        streamifier.createReadStream(req.file.buffer).pipe(stream);
      });
    };
    const result = await streamUpload(req);
    res.send(result);
  }
);
export default uploadRouter;
like image 156
Senzo Tshezi Avatar answered Dec 08 '25 00:12

Senzo Tshezi


Okay, so I found what my issue was and it looks like it might be your issue too. My environment variables were coming back as undefined and it turns out that they need to be imported into the file where your config is using import "dotenv/config.js";. Here is the StackOverflow thread for reference: Can't use dotenv with ES6 modules

like image 41
St3ph3n92 Avatar answered Dec 07 '25 22:12

St3ph3n92



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!