Skip to content
Go back

Handling File Uploads in Fastify Using Multipart

Handling File Uploads in Fastify Using Multipart

Introduction

File uploads are common in web applications. This guide shows how to accept and process multipart file uploads in Fastify using the fastify-multipart plugin.

Prerequisites

Step 1: Install the Plugin

npm install fastify-multipart

Step 2: Register Plugin

In src/server.ts:

import Fastify from "fastify";
import multipart from "fastify-multipart";

const app = Fastify({ logger: true });
app.register(multipart); 

app.post("/upload", async (req, reply) => {
  const parts = req.parts();
  for await (const part of parts) {
    if (part.file) {
      await pump(part.file, fs.createWriteStream(`uploads/${part.filename}`));
    }
  }
  reply.send({ status: "ok" });
});

app.listen({ port: 3000 });

Step 3: Handle Streams and Save Files

Install utility:

npm install pump

Use pump to pipe the file stream:

import { pump } from "pump";
import fs from "fs";

Step 4: Test Uploads

curl -F "file=@./path/to/file.png" http://localhost:3000/upload

Summary

With fastify-multipart, you can easily handle large file uploads as streams, ensuring efficient memory usage and scalability.


Share this post on:

Previous Post
Optimizing Node.js Server Performance with Clustering
Next Post
Implementing Rate Limiting in Fastify with Redis