MERN application for File Uploading

MERN application for File Uploading

Making a MERN (MongoDB, Express.js, React, Node.js) app for file uploading has a few steps. In this example, I'll show you how to make a simple MERN stack app with file uploading using Multer to manage file uploads on the server side. To keep it simple, I'll use create-react-app for the front end.

Step 1: Set Up the Server (Node.js and Express)

  1. Create a new Node.js project and install the necessary packages:

     mkdir mern-file-upload
     cd mern-file-upload
    
     # Initialize the project
     npm init -y
    
     # Install necessary packages
     npm install express mongoose multer
    
  2. Create a server file (server.js):

     const express = require('express');
     const mongoose = require('mongoose');
     const multer = require('multer');
     const path = require('path');
    
     const app = express();
     const PORT = process.env.PORT || 5000;
    
     // Connect to MongoDB (replace 'your-mongodb-uri' with your actual MongoDB connection string)
     mongoose.connect('your-mongodb-uri', { useNewUrlParser: true, useUnifiedTopology: true });
    
     // Define a file storage strategy for Multer
     const storage = multer.diskStorage({
       destination: './uploads',
       filename: (req, file, cb) => {
         cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
       }
     });
    
     const upload = multer({ storage });
    
     // Serve static files from the 'uploads' directory
     app.use('/uploads', express.static('uploads'));
    
     // Handle file upload
     app.post('/upload', upload.single('file'), (req, res) => {
       res.json({ file: req.file });
     });
    
     app.listen(PORT, () => {
       console.log(`Server is running on http://localhost:${PORT}`);
     });
    

Step 2: Set Up the Client (React)

  1. Create a new React app:

     npx create-react-app client
    
  2. Make a file upload component (FileUpload.js) in the src folder:

     import React, { useState } from 'react';
    
     const FileUpload = () => {
       const [file, setFile] = useState(null);
    
       const handleFileChange = (e) => {
         setFile(e.target.files[0]);
       };
    
       const handleFileUpload = async () => {
         try {
           const formData = new FormData();
           formData.append('file', file);
    
           const response = await fetch('http://localhost:5000/upload', {
             method: 'POST',
             body: formData
           });
    
           const data = await response.json();
           console.log('File uploaded:', data.file);
         } catch (error) {
           console.error('Error uploading file:', error);
         }
       };
    
       return (
         <div>
           <input type="file" onChange={handleFileChange} />
           <button onClick={handleFileUpload} disabled={!file}>
             Upload
           </button>
         </div>
       );
     };
    
     export default FileUpload;
    
  3. Update the src/App.js file to use the FileUpload component:

     import React from 'react';
     import './App.css';
     import FileUpload from './FileUpload';
    
     function App() {
       return (
         <div className="App">
           <h1>MERN File Upload</h1>
           <FileUpload />
         </div>
       );
     }
    
     export default App;
    

Step 3: Run the Application

  1. Start the server.

     node server.js
    
  2. Start the React app in another terminal:

     cd client
     npm start
    

Go to http://localhost:3000 in your browser to see the MERN File Upload app. Choose a file, click the "Upload" button, and the file will be sent to the server.

Be sure to change 'your-mongodb-uri' to your real MongoDB connection string. Also, remember to take care of security issues like proper authentication, authorization, and validation when using this in a production setting.