Crafting a Minimalist File Upload API with Node.js and Express
Need a simple file upload API without the overhead of a full-blown framework? Today, we’ll craft a calm, minimalist solution using Node.js and Express.
Just pure backend bliss.
Table of Contents
Why Keep It Simple?
A basic file upload service is a common sidekick:
Upload profile pictures
Submit documents
Store small attachments
By using only Node.js + Express with a sprinkle of Multer, we can avoid bloat and focus on clarity.
Project Setup
Let’s spin up a fresh project:
mkdir file-upload-api
cd file-upload-api
npm init -y
npm install express multer
Then create an entry file:
touch index.js
Building the API
- Create the Express Server
// index.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 3000;
// Set storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
}
});
const upload = multer({ storage });
// Middleware
app.use(express.json());
// Upload endpoint
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded.' });
}
res.status(201).json({ filename: req.file.filename });
});
// Start server
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
- Create the Express Server
Make sure there’s a folder to store uploaded files:
mkdir uploads
Testing the Upload
You can test the API using Postman or cURL: Using cURL:
curl -F "file=@/path/to/your/file.jpg" http://localhost:3000/upload
You should receive:
{
"filename": "timestamp-file.jpg"
}
And the file should appear inside the /uploads directory.
Using Postman:
- Create a new POST request to http://localhost:3000/upload
- Under “Body” select “form-data”
- Add a field named file
- Attach a file
- Hit Send!
Next Steps
This calm little project can be expanded:
* Add file type restrictions (only images, only PDFs)
* Limit file size
* Integrate cloud storage (S3, Azure Blob)
* Add simple authentication
🧘♂️ Like this kind of content?
Follow my dev blog → ZenOfCode
Or drop me a follow here on Dev.to 💬