Responsive Advertisement

How to upload file in cloudinary using express.js and multer

File Upload with Express.js, Cloudinary, and Multer

Step-by-Step Procedure to Upload Any File in Backend using Express.js, Cloudinary, and Multer

  1. Install all the packages:
    npm install express multer cloudinary dotenv
  2. Create an account in Cloudinary and keep these information in a .env file:
    // Cloudinary configuration
    CLOUDINARY_CLOUD_NAME=Your_cloudinary_name
    CLOUDINARY_API_KEY=Your_cloudinary_api_key
    CLOUDINARY_API_SECRET=Your_cloudinary_secret_key
  3. After installing these packages, create two files: index.js and multer-config.js.
  4. In multer-config.js file, write the basic multer configuration code:
    const multer = require('multer');
    const storage = multer.memoryStorage();  // store image in memory
    const upload = multer({ storage: storage });
    module.exports = upload;
  5. Use the multer mechanism in index.js file with a POST route '/upload':
    const express = require('express');
    const cloudinary = require('cloudinary').v2;
    require('dotenv').config();
    const upload = require('./multer-config');
    
    const app = express();
    
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    // Cloudinary configuration
    cloudinary.config({
        cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_API_SECRET,
    });
    
    app.post('/upload', upload.single('image'), (req, res) => {
        try {
            // Upload image to Cloudinary using stream
            const uploadStream = cloudinary.uploader.upload_stream({ folder: 'upload' }, (error, result) => {
                if (error) {
                    console.error(error);
                    return res.status(500).json({ error: 'Error uploading image to Cloudinary' });
                }
                // Send the Cloudinary URL in the response
                res.json({ imageUrl: result.secure_url });
            });
    
            // Pipe the file buffer to the uploadStream
            if (req.file && req.file.buffer) {
                uploadStream.end(req.file.buffer);
            } else {
                res.status(400).json({ error: 'No file uploaded' });
            }
        } catch (error) {
            console.error(error);
            res.status(500).json({ error: 'Error processing upload' });
        }
    });
    
    //Run server
    app.listen(5000, () => {
        console.log('Server is running on port 5000');
    });
  6. Now, you can hit the '/upload' route with a POST request and upload your file.

Congratulations ☺️✌️

Post a Comment

0 Comments