Uploading Images to Cloudinary with React and Express

Jainam bagrechaJainam bagrecha
4 min read

Certainly! Here's a blog post that covers uploading images to Cloudinary using a combination of React and an Express server. This approach is common when you want to handle image uploads on the server side before sending them to Cloudinary.


When building web applications that require image uploads, it's often more secure and scalable to handle these uploads on the server side rather than directly from the client. By using a server like Express in combination with Cloudinary, you can manage image uploads securely and efficiently. In this blog post, we'll walk through how to upload images to Cloudinary using React on the frontend and Express on the backend.

Prerequisites

Before we get started, ensure you have the following:

  • A basic understanding of React, Express, and JavaScript.

  • A Cloudinary account to get your API credentials.

  • Node.js installed on your machine.

Setting Up the Express Server

  1. Initialize Your Node.js Project

    First, let's set up a new Node.js project:

     mkdir cloudinary-upload-server
     cd cloudinary-upload-server
     npm init -y
    
  2. Install Required Packages

    Install the necessary packages, including Express, Cloudinary, CORS, and Multer for handling file uploads:

     npm install express cloudinary multer cors
    
  3. Configure Cloudinary in Express

    Create a server.js file in the root of your project and set up your Express server:

     const express = require('express');
     const multer = require('multer');
     const cloudinary = require('cloudinary').v2;
     const cors = require('cors');
    
     const app = express();
    
     // Middleware
     app.use(cors());
     app.use(express.json());
    
     // Configure Cloudinary
     cloudinary.config({
         cloud_name: 'your_cloud_name',
         api_key: 'your_api_key',
         api_secret: 'your_api_secret',
     });
    
     // Multer setup
     const storage = multer.memoryStorage();
     const upload = multer({ storage });
    
     // Image Upload Route
     app.post('/upload', upload.single('image'), async (req, res) => {
         try {
             const result = await cloudinary.uploader.upload_stream((error, result) => {
                 if (error) {
                     return res.status(500).send('Upload failed');
                 }
                 return res.status(200).json({ url: result.secure_url });
             }).end(req.file.buffer);
         } catch (err) {
             res.status(500).send('Server error');
         }
     });
    
     const PORT = process.env.PORT || 5000;
     app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
    

    Explanation:

    • Cloudinary Configuration: Your Cloudinary credentials (cloud_name, api_key, and api_secret) are configured here.

    • Multer Setup: Multer is configured to use memory storage, meaning that files will be stored in memory as buffers.

    • Upload Route: The /upload route handles image uploads. Multer captures the image, and it's uploaded to Cloudinary using Cloudinary's uploader.upload_stream method.

Setting Up the React Frontend

  1. Create a React App

    Create a new React application using Create React App:

     npx create-react-app cloudinary-upload-client
     cd cloudinary-upload-client
    
  2. Create the Image Upload Component

    Now, let's create a component that allows users to select an image and upload it to the Express server:

     import React, { useState } from 'react';
     import axios from 'axios';
    
     const ImageUpload = () => {
         const [image, setImage] = useState(null);
         const [url, setUrl] = useState('');
    
         const handleImageChange = (e) => {
             setImage(e.target.files[0]);
         };
    
         const handleSubmit = async (e) => {
             e.preventDefault();
             const formData = new FormData();
             formData.append('image', image);
    
             try {
                 const res = await axios.post('http://localhost:5000/upload', formData, {
                     headers: {
                         'Content-Type': 'multipart/form-data',
                     },
                 });
                 setUrl(res.data.url);
             } catch (err) {
                 console.error(err);
             }
         };
    
         return (
             <div>
                 <h2>Upload Image to Cloudinary</h2>
                 <form onSubmit={handleSubmit}>
                     <input type="file" onChange={handleImageChange} />
                     <button type="submit">Upload</button>
                 </form>
                 {url && (
                     <div>
                         <h3>Uploaded Image:</h3>
                         <img src={url} alt="Uploaded to Cloudinary" />
                     </div>
                 )}
             </div>
         );
     };
    
     export default ImageUpload;
    

Key Parts of the Component:

  • State Management: The image state stores the selected file, while the url state holds the Cloudinary URL of the uploaded image.

  • Image Selection: The handleImageChange function captures the selected file.

  • Form Submission: The handleSubmit function sends the image to the Express server using Axios. The server handles the upload to Cloudinary and returns the URL.

  1. Integrate the Component into Your App

    Use the ImageUpload component in your main App component:

     import React from 'react';
     import ImageUpload from './components/ImageUpload';
    
     function App() {
         return (
             <div className="App">
                 <h1>Cloudinary Image Upload with React and Express</h1>
                 <ImageUpload />
             </div>
         );
     }
    
     export default App;
    

Running the Application

  1. Start the Express Server

    In the cloudinary-upload-server directory, start the Express server:

     node server.js
    
  2. Start the React Application

    In the cloudinary-upload-client directory, start your React app:

     npm start
    
  3. Testing the Upload

    Open your browser and go to http://localhost:3000. Select an image file and upload it. The image will be sent to your Express server, uploaded to Cloudinary, and the URL will be displayed on the page.

Conclusion

In this tutorial, we covered how to upload images to Cloudinary using a combination of React and Express. By handling the upload on the server side with Express, you can better secure your application and keep sensitive credentials safe. Using Cloudinary's API, you can easily manage and deliver images in your web application.

Further Reading


Subscribe to My Newsletter

If you enjoyed this article and want more content like this, consider subscribing to my newsletter. Get the latest updates, tutorials, and tips straight to your inbox!

Connect with Me

If you have any questions or feedback, feel free to reach out on LinkedIn, Twitter, or GitHub.


0
Subscribe to my newsletter

Read articles from Jainam bagrecha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jainam bagrecha
Jainam bagrecha

I'm Jainam Bagrecha, a passionate web developer with expertise in modern web technologies. My goal is to empower developers by providing clear, actionable content that makes complex concepts easier to understand. Follow along as I explore the latest trends and best practices in web development, and let's build something amazing together.