,

Creating a MERN Stack Image Gallery App with Drag and Drop Image Upload to Cloudinary #shorts

Posted by


In this tutorial, we will be building a MERN stack image gallery app that allows users to upload images via drag and drop functionality. We will also be implementing image storage and retrieval using Cloudinary, a cloud-based image and video management platform.

Prerequisites:

  • Basic knowledge of React, Node.js, and MongoDB
  • Node.js and MongoDB installed on your machine
  • Basic knowledge of HTML and CSS

Step 1: Setting up the backend

  1. Create a new directory for your project and navigate to it in your terminal.

  2. Initialize a new Node.js project by running the following command:

    npm init -y
  3. Install the necessary dependencies for the backend using the following command:

    npm install express mongoose multer cloudinary dotenv
  4. Create a new file named server.js and require the necessary modules:
    
    const express = require('express');
    const mongoose = require('mongoose');
    const multer = require('multer');
    const cloudinary = require('cloudinary').v2;
    const dotenv = require('dotenv');

dotenv.config();

const app = express();

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
});

// Set up Multer for file uploads
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, ‘uploads/’);
},
filename: function(req, file, cb) {
cb(null, file.originalname);
},
});

const upload = multer({ storage: storage });

// Set up 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,
});

// Start the server
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});


5. Create a `.env` file in your project's root directory and add your MongoDB connection string and Cloudinary credentials:

MONGODB_URI=your-mongodb-connection-string
CLOUDINARY_CLOUD_NAME=your-cloudinary-cloud-name
CLOUDINARY_API_KEY=your-cloudinary-api-key
CLOUDINARY_API_SECRET=your-cloudinary-api-secret
PORT=5000


Step 2: Setting up the frontend

1. Create a new directory named `client` in your project's root directory and navigate to it in your terminal.

2. Initialize a new React project by running the following command:

npx create-react-app .


3. Install the necessary dependencies for the frontend using the following command:

npm install axios react-dropzone-uploader


4. Create a new file named `ImageGallery.js` in the `src` directory and add the following code:
```jsx
import React from 'react';

const ImageGallery = () => {
  return (
    <div>
      <h1>Image Gallery</h1>
    </div>
  );
};

export default ImageGallery;
  1. Update the App.js file in the src directory to include the ImageGallery component:
    
    import React from 'react';
    import ImageGallery from './ImageGallery';

function App() {
return (

);
}

export default App;


Step 3: Implementing image upload functionality

1. Update the `ImageGallery.js` file to include the image upload functionality:
```jsx
import React from 'react';
import Dropzone from 'react-dropzone-uploader';
import axios from 'axios';

const ImageGallery = () => {
  const getUploadParams = ({ meta }) => {
    const url = 'https://api.cloudinary.com/v1_1/your-cloudinary-cloud-name/upload';
    return { url, meta: { fileUrl: `${url}/${encodeURIComponent(meta.name)}` } };
  };

  const handleChangeStatus = ({ meta, file, xhr }, status) => {
    if (status === 'done') {
      console.log('File uploaded!', xhr.response);
      // Save the image URL to the database
      axios.post('http://localhost:5000/images', { imageUrl: JSON.parse(xhr.response).secure_url });
    }
  };

  return (
    <div>
      <h1>Image Gallery</h1>
      <Dropzone
        getUploadParams={getUploadParams}
        onChangeStatus={handleChangeStatus}
        accept="image/*"
        inputContent="Drop or click to upload images"
      />
    </div>
  );
};

export default ImageGallery;
  1. Update the server.js file to include a route for handling image uploads:
    app.post('/images', upload.single('image'), async (req, res) => {
    try {
    const result = await cloudinary.uploader.upload(req.file.path);
    // Save the image URL to the database
    // Create a new image document in MongoDB
    res.json({ imageUrl: result.secure_url });
    } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Failed to upload image' });
    }
    });

Step 4: Running the application

  1. Start the backend server by running the following command in the root directory of your project:

    node server.js
  2. Start the frontend server by running the following command in the client directory:

    npm start
  3. Visit http://localhost:3000 in your web browser to view the image gallery app.

Conclusion:

In this tutorial, we have successfully built a MERN stack image gallery app that allows users to upload images via drag and drop functionality. We have also implemented image storage and retrieval using Cloudinary. Feel free to customize the app further by adding features such as image filtering, image editing, and user authentication.