Reputation: 149
I am using Cloudinary to upload images using Multer in my Nodejs, Expressjs, and Typescript applications. In my route req.file a file is coming from the frontend but it is uploading to Cloudinary using uploadImage function it is giving me the console aggregate error I set everything from documentation from Cloudinary beacuse I am uploading the base64 string to Cloudinary. How to solve this problem. Please help to solve this error.
Follow the link of Cloudinary documentation to upload file in Nodejs using Multer which I am using
Blow the image of error what am I getting in when upload file to cloudinary.
upload.ts
import multer from "multer";
const storage = multer.memoryStorage();
export const upload = multer({ storage: storage });
cloudinary.ts
import { v2 as cloudinary, UploadApiResponse } from 'cloudinary'
import dotenv from "dotenv";
import { ErrorHandler } from './errorHandler';
dotenv.config()
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_SECRET_KEY
});
export interface UploadedFile extends Express.Multer.File { }
export const uploadImage = async (file: UploadedFile) => {
try {
const b64 = Buffer.from(file.buffer).toString("base64");
const dataURI = "data:" + file.mimetype + ";base64," + b64;
const result: UploadApiResponse = await cloudinary.uploader.upload(dataURI);
return {
id: result.public_id,
url: result.secure_url
}
} catch (error: any) {
console.error('Error uploading image:', error.message);
throw new ErrorHandler(500, error.message)
}
};
export { cloudinary }
routes.ts
import express, { NextFunction, Request, Response } from "express";
import { upload } from "../middlewares";
import { ErrorHandler, UploadedFile, uploadImage } from "../utils";
import { bannerService } from "../services";
const router = express.Router();
router.post("/upload-image", upload.single("image"), async (req: Request, res: Response, next: NextFunction) => {
try {
const image = await uploadImage(req.file as UploadedFile)
res.status(200).send(image)
} catch (error: any) {
return next(new ErrorHandler(500, error.message))
}
})
export default router
Upvotes: 0
Views: 148
Reputation: 1
I was facing the same problem on my local development computer but when I deployed it to a live server on render.com, I was able to upload the images to Cloudinary. I can't really point out exactly why this happening.
Also note that this is only happening when using node v20.11.1. Switching it to v18.20.3 solves the problem and I'm able to use it on my local local development computer.
Upvotes: 0