Building a File Upload API in MERN
Sure! Here's a step-by-step guide to building a File Upload API using the MERN stack (MongoDB, Express.js, React, Node.js):
π§ Tech Stack
Frontend: React
Backend: Node.js with Express.js
Database: MongoDB (to store file metadata)
File Storage: Local filesystem (for simplicity) or cloud (e.g., AWS S3 – optional upgrade)
π Project Structure
css
Copy
Edit
mern-file-upload/
├── backend/
│ ├── uploads/
│ ├── routes/
│ │ └── upload.js
│ ├── app.js
│ └── ...
└── frontend/
└── src/
└── components/
└── FileUpload.js
π ️ 1. Backend Setup (Node.js + Express)
1.1 Initialize Project
bash
Copy
Edit
mkdir backend && cd backend
npm init -y
npm install express multer mongoose cors
1.2 app.js - Main Express Server
js
Copy
Edit
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const uploadRoute = require('./routes/upload');
const app = express();
const PORT = 5000;
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static('uploads'));
app.use('/api/upload', uploadRoute);
mongoose.connect('mongodb://localhost:27017/fileuploads', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
1.3 routes/upload.js
js
Copy
Edit
const express = require('express');
const multer = require('multer');
const router = express.Router();
// Storage config
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname),
});
const upload = multer({ storage });
// File Upload Route
router.post('/', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
res.json({
filename: req.file.filename,
path: req.file.path,
size: req.file.size,
mimetype: req.file.mimetype,
});
});
module.exports = router;
π» 2. Frontend Setup (React)
2.1 Create React App
bash
Copy
Edit
npx create-react-app frontend
cd frontend
npm install axios
2.2 FileUpload.js Component
jsx
Copy
Edit
import React, { useState } from 'react';
import axios from 'axios';
const FileUpload = () => {
const [file, setFile] = useState(null);
const [uploadedData, setUploadedData] = useState(null);
const handleChange = (e) => {
setFile(e.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append('file', file);
try {
const res = await axios.post('http://localhost:5000/api/upload', formData);
setUploadedData(res.data);
} catch (err) {
console.error(err);
}
};
return (
<div>
<h2>Upload File</h2>
<input type="file" onChange={handleChange} />
<button onClick={handleUpload}>Upload</button>
{uploadedData && (
<div>
<h4>Uploaded:</h4>
<p>File: {uploadedData.filename}</p>
<p>Type: {uploadedData.mimetype}</p>
<a href={`http://localhost:5000/${uploadedData.path}`} target="_blank" rel="noreferrer">View File</a>
</div>
)}
</div>
);
};
export default FileUpload;
2.3 Use the Component
In App.js:
jsx
Copy
Edit
import React from 'react';
import FileUpload from './components/FileUpload';
function App() {
return (
<div className="App">
<FileUpload />
</div>
);
}
export default App;
π§ͺ Testing
Start MongoDB (mongod).
Run the backend:
bash
Copy
Edit
node app.js
Run the frontend:
bash
Copy
Edit
npm start
Open browser at http://localhost:3000 and upload a file.
π Next Steps / Improvements
Validate file types and sizes
Store file metadata in MongoDB
Add progress bar
Use cloud storage like AWS S3 or Cloudinary
Add user authentication
Learn MERN Stack Course in Hyderabad
Read More
Setting Up WebSockets with Node and Express
Caching Data with Redis in Node.js
Creating Relationships in MongoDB using Mongoose
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment