DEV Community

Mayank Bhugra
Mayank Bhugra

Posted on

# MERN Stack problem

1 Problem statement: I have to store images somewhere and than add there link in mongodb. Can anyone help me regarding this problem as i am new in fullstack so i want some advice regarding this.

Top comments (2)

Collapse
 
shanvi_soni profile image
Shanvi Soni

Theoretical Steps
Choose a Storage Solution:

Cloud Storage: Use a cloud service (like Cloudinary, AWS S3, or Google Cloud Storage) to store your images. These services allow you to upload images and retrieve URLs for those images.
Local Storage: Alternatively, you could store images locally on your server's filesystem, but this is less scalable and not recommended for production environments.
Set Up Your Backend:

Use a backend framework (like Express.js) to create an API that handles image uploads.
Multer is a middleware for handling multipart/form-data, which is used for file uploads.
Implement Image Upload Logic:

When a user uploads an image, the image is processed by the backend server.
If using cloud storage, the server will upload the image to the cloud storage provider.
Upon successful upload, the cloud provider will return a URL for the uploaded image.
Store Image URL in MongoDB:

Use a database (like MongoDB) to store data about the images.
Create a schema that includes fields for the image URL and any other relevant metadata (like image name, upload date, etc.).
Save the URL returned from the cloud storage provider into the MongoDB database.
Frontend Implementation:

Create a user interface that allows users to select and upload images.
Use HTML forms to handle file input and submit the images to the backend API.
Upon successful upload, provide feedback to the user (e.g., displaying the uploaded image or showing a success message).
Consider Security and Optimization:

Validate and sanitize user input to prevent security issues (like file type checks).
Consider implementing caching strategies to speed up the retrieval of images.
Ensure your application can handle multiple concurrent uploads efficiently.

npm install express mongoose multer cloudinary dotenv
// server.js
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();
const PORT = process.env.PORT || 5000;

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

// Cloudinary configuration
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
});

// Multer setup
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// Image Schema
const ImageSchema = new mongoose.Schema({
url: String,
});

const Image = mongoose.model('Image', ImageSchema);

// Upload image route
app.post('/upload', upload.single('image'), async (req, res) => {
try {
const result = await cloudinary.uploader.upload_stream(req.file.buffer);
const newImage = new Image({ url: result.secure_url });
await newImage.save();
res.status(200).json({ message: 'Image uploaded successfully', url: newImage.url });
} catch (error) {
res.status(500).json({ error: error.message });
}
});

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

Upload



document.getElementById('uploadForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const response = await fetch('/upload', {
        method: 'POST',
        body: formData,
    });
    const data = await response.json();
    console.log(data);
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gulshanaggarwal profile image
Gulshan Aggarwal

Option-1 You can upload images to your server using multer(npm package) and then store your image link to mongodb.

Option-2 Upload image to firebase, get download link and store it to mongodb.

Option -3 AWS S3 storage but for beginners it's not recommended.