A few days ago, I needed to handle file uploads in a Node.js application. Like most people, I initially used multer
, but soon realized that it didn’t meet the needs of my business logic. While multer
uploads files (e.g., images, PDFs) to the server, it doesn't handle my use case well.
Specifically, if an error occurs while validating data in the database, I have to delete the file manually, which is far from ideal. This approach just didn’t feel right, so I decided to build a custom solution. And that's how ap-multipart
was born.
ap-multipart
?There’s nothing overly complex or special about it—ap-multipart
does exactly what you’d expect: it parses multipart form data, but without relying on external libraries. It's lightweight, simple to use, and integrates smoothly into your Express app.
Here's what's great about it:
No external dependencies: It’s minimalistic, which means fewer dependencies and a faster, more secure application.
Automatic integration: Fields are automatically added to req.body
and files are added to req.files
.
Flexible file handling: You can validate business logic first and create the file afterward, eliminating the need to delete files on validation failures.
ap-multipart
It’s really simple to get started. Just follow the steps below:
npm install ap-multipart
Ensure that express.json()
is used before ap-multipart()
.
const express = require("express");
const apMultiPart = require("ap-multipart");
const app = express();
app.use(express.json());
app.use(apMultiPart());
Once you’ve set it up, req.body
will contain form fields, and req.files
will contain your uploaded files.
app.post("/", async (req, res, next) => {
const uploadedFiles = req.files;
// Example: Access the first uploaded file
const firstFile = uploadedFiles[0];
const fileName = firstFile.filename;
const fileData = firstFile.data;
// Process the file after validating your business logic
const writable = await fs.createWriteStream(fileName);
writable.write(fileData);
writable.end();
res.json({ message: "Files received successfully!" });
});
Note: req.files
will be an array of the uploaded files, and each file object will have the following fields:
filename
: The original filename of the uploaded file.
extension
: The file extension (e.g., .jpg
, .png
).
mimetype
: The MIME content type of the file (e.g., image/jpeg
, application/pdf
).
size
: The size of the file in kilobytes (KB) for easy reference.
data
: A buffer containing the raw file data, allowing for advanced handling.
With ap-multipart
, you can easily implement file handling while ensuring your business logic is validated before saving any files. This eliminates the hassle of cleaning up files in case of validation errors, making your app more reliable and efficient.
So, what do you think? Does this package make file uploads simpler for you, or would you like to see any improvements?