AP-Multipart: A Lightweight Alternative to Multer for Handling File Uploads

aman pareek author
Aman Pareek

Published 20/01/2025

Updated 20/01/2025

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.

What's Special About 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:


How to Use ap-multipart

It’s really simple to get started. Just follow the steps below:

Step 1: Install the package

npm install ap-multipart

Step 2: Set up your Express app

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());

Step 3: Handling the upload

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:


Why It Matters

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?