Hey there! π I recently ran into a bit of a challenge while creating my portfolio. I had a blog page with cover images, and initially, I used Multer to upload images to a local folder on my server. Everything worked like a charm until I decided to host my site on Render directly from GitHub. The images weren't uploading to GitHub, which wasn't surprising.
I decided to use cloud-based storage and opted for Cloudinary. In this guide, I'll walk you through how I set up Cloudinary on my server integrated it with Multer, and saved the image links to MongoDB.Solving my problem.
I started by installing the dependencies.
npm install multer cloudinary dotenv
Before diving into code, I had to set up Cloudinary account and grab my API key, API secret, and cloud name from the dashboard. I added a .env file in my server's root folder and populated it like this:
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
CLOUDINARY_CLOUD_NAME=your_cloud_name
Next, I created a utils folder and within it, a file named cloudinary.js to configure my Cloudinary setup:
// utils/cloudinary.js
const cloudinary = require('cloudinary').v2;
require('dotenv').config();
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
module.exports = cloudinary;
Now, in my root folder, I set up a middleware folder, and within it I Created a file named multer.js to configure Multer:
// multer.js
const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
module.exports = upload;
imported these two files into my post controllers like this:
// Your post controllers file
const cloudinary = require('./utils/cloudinary');
const upload = require('./multer');
Now, in my post route, I can upload a file and wait until it's uploaded using a promise before adding the rest of the form data from the body. Here's how my post route looks:
Top comments (0)