Web Development

How to Upload Large Files to a Website Using Chunked Uploads

Uploading large files to a website can be challenging. Users may experience slow uploads, network interruptions, or failed requests when uploading videos,…

D
DevByteTechnical Author
Published
23 min read3 views
How to Upload Large Files to a Website Using Chunked Uploads

Uploading a small image to a website is usually straightforward. You select a file, send it to the backend, and store it on your server or cloud storage.

But things get more complicated when users need to upload large videos, ZIP files, backups, datasets, or other files that are hundreds of megabytes or several gigabytes in size.

Imagine you're building a video-sharing platform. A user selects a 2 GB video and starts uploading it. After several minutes, their internet connection drops when the upload is 90% complete. If your application sends the entire file as one request, the user might have to start again from the beginning.

That's not a great experience.

One way to solve this problem is chunked file uploading. Instead of sending the entire file in one request, we divide it into smaller pieces, upload those pieces separately, and combine them on the server after all the pieces arrive.

I've used this approach as a useful pattern to understand when building applications that need reliable file uploads. In this article, we'll look at how chunked uploads work and implement a basic version using Node.js, Express, and JavaScript.

What Is Chunked File Uploading?

Chunked uploading is a technique in which a large file is divided into smaller parts called chunks. Each chunk is uploaded separately, and the backend combines the parts to reconstruct the original file.

For example, suppose a user wants to upload a 100 MB video. Instead of sending all 100 MB in a single HTTP request, the frontend divides it into chunks of 5 MB each.

The upload would look something like this:

Original file: 100 MB
        |
        v
Split into smaller chunks
        |
        +---- Chunk 1: 5 MB
        +---- Chunk 2: 5 MB
        +---- Chunk 3: 5 MB
        +---- ...
        +---- Chunk 20: 5 MB
        |
        v
Upload chunks to the backend
        |
        v
Store chunks temporarily
        |
        v
Combine chunks in the correct order
        |
        v
Original file reconstructed

The server receives 20 smaller pieces instead of one large request. Once all the chunks have been uploaded and verified, it combines them into the original file.

The chunk size isn't fixed. You might choose 1 MB, 5 MB, or 10 MB depending on your application, network conditions, infrastructure, and storage provider.

The important thing is that both the frontend and backend agree on how the upload is organized.

Why Should We Use Chunked Uploads?

You might be wondering why we need this approach when a normal file upload already works.

For small files, a regular upload is usually sufficient. Chunking becomes more useful when files are large, connections are unreliable, or users need better control over upload progress.

Here are some practical benefits.

1. Better handling of large files

Sending a multi-gigabyte file in one request can put pressure on your application server, reverse proxy, and network connection.

Chunking lets your application process smaller requests rather than requiring one enormous request body.

However, chunking doesn't automatically eliminate memory usage or server limits. You still need to configure your backend to handle each chunk efficiently.

2. Retry failed chunks

Suppose a 500 MB file is divided into 100 chunks of 5 MB each.

If chunk 65 fails, the application can retry that chunk instead of uploading the entire 500 MB file again.

This can save a significant amount of time when users have unstable internet connections.

3. Show upload progress

Your frontend can track how many chunks have been uploaded and display progress to the user.

For example:

Uploading video.mp4

[██████████████░░░░░░] 70%

70 MB of 100 MB uploaded

You can also show the file name, upload speed, remaining work, and retry status.

4. Support resumable uploads

Chunked uploads can be extended to support resumability.

If the user closes their browser or loses their connection, the application can identify which chunks were already uploaded and send only the missing ones when the user resumes.

Important: Chunking alone does not make an upload resumable. You need to persist upload metadata and provide an endpoint or mechanism for checking which chunks have already been received.

5. Improve the user experience

Users don't necessarily care how your backend stores files. They care about whether uploads work reliably.

A progress bar, automatic retries, and the ability to resume an interrupted upload make the experience much better.

How Does a Chunked Upload Work?

Before writing the code, let's understand the complete flow.

Step 1: The user selects a file.

The browser receives a File object containing the file's metadata and access to its contents.

Step 2: The frontend divides the file into chunks.

JavaScript provides the slice() method, which allows us to read portions of a file without loading the entire file into memory.

Step 3: The frontend uploads each chunk.

Each request includes the chunk data and metadata such as the upload ID, chunk index, and total number of chunks.

Step 4: The backend stores the chunks.

The server stores each piece temporarily using a predictable index, such as 0, 1, 2, and so on.

Step 5: The frontend requests completion.

After all chunks have been uploaded, the frontend calls a completion endpoint.

Step 6: The backend validates and combines the chunks.

The server checks that every expected chunk exists and combines them in the correct order.

Step 7: The completed file is stored.

The application can then move the file to permanent storage, such as an object-storage service, and save its metadata in a database.

Let's implement a basic version of this flow.

Step 1: Create a Node.js Project

First, create a new project:

mkdir chunked-upload-demo
cd chunked-upload-demo

npm init -y
npm install express multer

We'll use:

  • Node.js: Runs our backend.

  • Express: Handles the HTTP endpoints.

  • Multer: Parses incoming multipart form-data requests.

  • File system APIs: Store temporary chunks and assemble the completed file.

Create the following structure:

chunked-upload-demo/
├── uploads/
├── temp/
├── server.js
├── package.json
└── public/
    ├── index.html
    └── app.js

The uploads directory will contain completed files, while temp will hold chunks during the upload process.

Create the directories if they don't already exist. We'll also make the backend create them automatically.

Step 2: Divide the File Into Chunks

Let's start with the frontend logic.

In JavaScript, the File object inherits from Blob, which provides a slice() method.

We can use it to extract a specific byte range from a file.

const CHUNK_SIZE = 5 * 1024 * 1024; // 5 MB

function splitFileIntoChunks(file) {
  const chunks = [];

  for (let start = 0; start < file.size; start += CHUNK_SIZE) {
    const end = Math.min(start + CHUNK_SIZE, file.size);

    chunks.push(file.slice(start, end));
  }

  return chunks;
}

Let's understand what happens here.

First, we define a chunk size of 5 MB.

Next, we loop through the file, moving forward by 5 MB each time. The slice() method extracts the current section.

We use Math.min() to ensure that the final chunk doesn't extend beyond the end of the file.

For a 12 MB file, the result would be approximately:

Chunk 0: 5 MB
Chunk 1: 5 MB
Chunk 2: 2 MB

Notice that we don't need to create a new physical file for every chunk in the browser. Each slice is a Blob representing part of the original file.

This also means we can upload each piece without reading the entire file into browser memory first.

Step 3: Build the Backend Using Express

Now let's implement the server.

Our backend needs three main endpoints:

Endpoint

Purpose

POST /api/uploads/:uploadId/chunks

Receive and store one chunk

GET /api/uploads/:uploadId

Check which chunks have been uploaded

POST /api/uploads/:uploadId/complete

Validate and assemble the final file

We'll also create a helper function to validate upload IDs and another to sanitize file names.

Create server.js:

const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs/promises");
const { createWriteStream } = require("fs");
const { randomUUID } = require("crypto");
const { pipeline } = require("stream/promises");

const app = express();

const PORT = 3000;

const TEMP_DIR = path.join(__dirname, "temp");
const UPLOAD_DIR = path.join(__dirname, "uploads");
const PUBLIC_DIR = path.join(__dirname, "public");

const CHUNK_SIZE = 5 * 1024 * 1024;
const MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024;

app.use(express.json({ limit: "100kb" }));
app.use(express.static(PUBLIC_DIR));

const storage = multer.memoryStorage();

const upload = multer({
  storage,
  limits: {
    fileSize: CHUNK_SIZE,
    files: 1,
  },
});

function isValidUploadId(uploadId) {
  return /^[0-9a-f-]{36}$/i.test(uploadId);
}

function sanitizeFileName(fileName) {
  if (typeof fileName !== "string" || !fileName.trim()) {
    throw new Error("A valid file name is required");
  }

  const safeName = path
    .basename(fileName)
    .replace(/[^a-zA-Z0-9._-]/g, "_")
    .slice(0, 180);

  if (!safeName || safeName === "." || safeName === "..") {
    throw new Error("Invalid file name");
  }

  return safeName;
}

function getUploadDirectory(uploadId) {
  if (!isValidUploadId(uploadId)) {
    throw new Error("Invalid upload ID");
  }

  return path.join(TEMP_DIR, uploadId);
}

async function ensureDirectories() {
  await fs.mkdir(TEMP_DIR, { recursive: true });
  await fs.mkdir(UPLOAD_DIR, { recursive: true });
}

Let's look at a few important decisions.

Why use Multer?

Multer handles multipart form-data requests, which is a common format for uploading files through a browser.

We've configured it to accept only one file per request and limit that file to 5 MB.

Because the chunk size is also 5 MB, the frontend and backend use matching limits.

Why use a generated upload ID?

Every upload needs an identifier so that chunks belonging to different files don't get mixed together.

The frontend will generate a UUID for each upload.

The backend validates its format before using it to construct a temporary directory path.

In a production application, you must also associate the upload ID with the authenticated user and verify ownership on every endpoint. A UUID is an identifier, not an authorization mechanism.

Why use path.basename()?

Never trust a file name received from the browser.

A malicious client could submit a name containing path traversal sequences or unexpected characters.

Using a sanitized name helps prevent the supplied file name from being used to write outside the intended directory.

This is only one layer of protection. Production applications should also validate content, permissions, and storage destinations.

Step 4: Create the Chunk Upload Endpoint

Now we'll add the endpoint that receives individual chunks.

Append the following code to server.js:

app.post(
  "/api/uploads/:uploadId/chunks",
  upload.single("chunk"),
  async (req, res) => {
    try {
      const { uploadId } = req.params;

      if (!isValidUploadId(uploadId)) {
        return res.status(400).json({
          message: "Invalid upload ID",
        });
      }

      const chunkIndex = Number(req.body.chunkIndex);
      const totalChunks = Number(req.body.totalChunks);
      const fileSize = Number(req.body.fileSize);

      if (
        !Number.isSafeInteger(chunkIndex) ||
        !Number.isSafeInteger(totalChunks) ||
        !Number.isSafeInteger(fileSize) ||
        totalChunks < 1 ||
        chunkIndex < 0 ||
        chunkIndex >= totalChunks ||
        fileSize < 1 ||
        fileSize > MAX_FILE_SIZE
      ) {
        return res.status(400).json({
          message: "Invalid chunk metadata",
        });
      }

      const expectedChunks = Math.ceil(fileSize / CHUNK_SIZE);

      if (totalChunks !== expectedChunks) {
        return res.status(400).json({
          message: "Chunk count does not match file size",
        });
      }

      if (!req.file) {
        return res.status(400).json({
          message: "Chunk data is required",
        });
      }

      const expectedChunkSize =
        chunkIndex === totalChunks - 1
          ? fileSize - chunkIndex * CHUNK_SIZE
          : CHUNK_SIZE;

      if (req.file.size !== expectedChunkSize) {
        return res.status(400).json({
          message: "Unexpected chunk size",
        });
      }

      const uploadDirectory = getUploadDirectory(uploadId);

      await fs.mkdir(uploadDirectory, {
        recursive: true,
      });

      const chunkPath = path.join(
        uploadDirectory,
        `${chunkIndex}.part`
      );

      // Writing the same chunk index again makes retries idempotent.
      await fs.writeFile(chunkPath, req.file.buffer, {
        flag: "w",
      });

      return res.status(200).json({
        message: "Chunk uploaded successfully",
        chunkIndex,
      });
    } catch (error) {
      console.error("Chunk upload error:", error);

      return res.status(500).json({
        message: "Failed to upload chunk",
      });
    }
  }
);

This endpoint receives one chunk at a time.

The frontend sends the chunk as a multipart field named chunk. It also sends the chunk index, total number of chunks, and original file size.

The backend checks that the metadata is consistent and verifies the chunk's expected size before saving it.

For example, a 12 MB file split into 5 MB chunks should contain three chunks:

0.part  -> 5 MB
1.part  -> 5 MB
2.part  -> 2 MB

The chunks are saved inside a directory associated with the upload ID.

Using the chunk index in the file name makes it possible to identify missing pieces and combine the chunks in the correct order.

One important detail: This example uses Multer's memory storage, so each individual chunk is buffered in server memory before being written to disk. That is manageable for small, bounded chunks, but a production service handling many concurrent uploads may benefit from streaming each request directly to temporary storage.

Step 5: Check Which Chunks Have Already Uploaded

If we want to support resumable uploads, the frontend needs a way to find out which chunks the server already has.

Let's create a status endpoint.

app.get("/api/uploads/:uploadId", async (req, res) => {
  try {
    const { uploadId } = req.params;

    if (!isValidUploadId(uploadId)) {
      return res.status(400).json({
        message: "Invalid upload ID",
      });
    }

    const uploadDirectory = getUploadDirectory(uploadId);

    let files;

    try {
      files = await fs.readdir(uploadDirectory);
    } catch (error) {
      if (error.code === "ENOENT") {
        return res.json({
          uploadedChunks: [],
        });
      }

      throw error;
    }

    const uploadedChunks = files
      .filter((file) => /^\d+\.part$/.test(file))
      .map((file) => Number(file.replace(".part", "")))
      .sort((a, b) => a - b);

    return res.json({
      uploadedChunks,
    });
  } catch (error) {
    console.error("Upload status error:", error);

    return res.status(500).json({
      message: "Could not retrieve upload status",
    });
  }
});

Suppose the browser previously uploaded chunks 0, 1, 2, and 3 before losing its connection.

When it requests the status endpoint, the server might return:

{
  "uploadedChunks": [0, 1, 2, 3]
}

The frontend can then skip those chunks and upload the remaining ones.

This endpoint provides the information needed for resuming, but a complete resumable-upload implementation must also persist the upload ID and file metadata on the client and server. It should reject attempts to reuse an upload ID with a different file or incompatible chunk configuration.

Step 6: Combine the Chunks Into the Original File

Once all the chunks have arrived, we need to reconstruct the file.

We must do this in the original order. Combining chunks in the wrong order will corrupt the resulting file.

Add the following completion endpoint:

app.post(
  "/api/uploads/:uploadId/complete",
  async (req, res) => {
    let outputPath;

    try {
      const { uploadId } = req.params;

      if (!isValidUploadId(uploadId)) {
        return res.status(400).json({
          message: "Invalid upload ID",
        });
      }

      const { totalChunks, fileName, fileSize } = req.body;

      if (
        !Number.isSafeInteger(totalChunks) ||
        !Number.isSafeInteger(fileSize) ||
        totalChunks < 1 ||
        fileSize < 1 ||
        fileSize > MAX_FILE_SIZE ||
        totalChunks !== Math.ceil(fileSize / CHUNK_SIZE)
      ) {
        return res.status(400).json({
          message: "Invalid completion metadata",
        });
      }

      const safeName = sanitizeFileName(fileName);
      const uploadDirectory = getUploadDirectory(uploadId);

      // Check every expected chunk before assembling the file.
      for (let index = 0; index < totalChunks; index++) {
        const chunkPath = path.join(
          uploadDirectory,
          `${index}.part`
        );

        try {
          await fs.access(chunkPath);
        } catch {
          return res.status(400).json({
            message: `Chunk ${index} is missing`,
          });
        }
      }

      outputPath = path.join(
        UPLOAD_DIR,
        `${randomUUID()}-${safeName}`
      );

      let combinedSize = 0;

      // Append chunks sequentially in their original order.
      for (let index = 0; index < totalChunks; index++) {
        const chunkPath = path.join(
          uploadDirectory,
          `${index}.part`
        );

        const stats = await fs.stat(chunkPath);

        const expectedChunkSize =
          index === totalChunks - 1
            ? fileSize - index * CHUNK_SIZE
            : CHUNK_SIZE;

        if (stats.size !== expectedChunkSize) {
          throw new Error(`Invalid size for chunk ${index}`);
        }

        combinedSize += stats.size;

        await pipeline(
          require("fs").createReadStream(chunkPath),
          createWriteStream(outputPath, {
            flags: index === 0 ? "w" : "a",
          })
        );
      }

      if (combinedSize !== fileSize) {
        throw new Error("Final file size does not match");
      }

      await fs.rm(uploadDirectory, {
        recursive: true,
        force: true,
      });

      return res.status(200).json({
        message: "File uploaded successfully",
        fileName: safeName,
        size: combinedSize,
      });
    } catch (error) {
      console.error("File assembly error:", error);

      // Remove a partially assembled output file.
      if (outputPath) {
        await fs.rm(outputPath, { force: true }).catch(() => {});
      }

      return res.status(500).json({
        message: "Failed to assemble uploaded file",
      });
    }
  }
);

ensureDirectories()
  .then(() => {
    app.listen(PORT, () => {
      console.log(`Server running on http://localhost:${PORT}`);
    });
  })
  .catch((error) => {
    console.error("Failed to initialize directories:", error);
    process.exit(1);
  });

Let's understand the assembly logic.

First, the backend checks whether every expected chunk exists. It then verifies each chunk's size and reads the chunks sequentially.

The first chunk opens the destination file in write mode. Every subsequent chunk is appended to the same file.

We're using streams to copy each chunk instead of loading all the chunks into one large buffer. This helps keep the memory requirements of the assembly process relatively low.

After combining the chunks, the backend checks the final size and removes the temporary chunk directory.

The resulting file is stored in the uploads directory.

For this demonstration, the completion endpoint returns the file name and size rather than exposing a public download URL.

A production consideration

This code is a teaching example, not a complete production upload service. It does not persist upload metadata in a database, enforce user ownership, lock concurrent completion requests, or atomically publish completed files.

A production implementation should address these concerns and ensure that a partially assembled file is never treated as a completed upload. It should also clean up incomplete uploads that have been abandoned.

Step 7: Create the Frontend Upload Interface

Now let's build a basic frontend that allows users to select a file and upload it in chunks.

Create public/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>Chunked File Upload</title>
</head>
<body>
  <h1>Upload a Large File</h1>

  <input type="file" id="fileInput" />

  <button id="uploadButton">Upload File</button>

  <p id="status"></p>

  <progress id="progress" value="0" max="100"></progress>

  <script src="/app.js"></script>
</body>
</html>

Next, create public/app.js:

const CHUNK_SIZE = 5 * 1024 * 1024;

const fileInput = document.getElementById("fileInput");
const uploadButton = document.getElementById("uploadButton");
const statusElement = document.getElementById("status");
const progressElement = document.getElementById("progress");

async function uploadFile(file) {
  const uploadId = crypto.randomUUID();

  const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

  let uploadedBytes = 0;

  for (let index = 0; index < totalChunks; index++) {
    const start = index * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE, file.size);

    const chunk = file.slice(start, end);

    const formData = new FormData();

    formData.append("chunk", chunk, "chunk.part");
    formData.append("chunkIndex", String(index));
    formData.append("totalChunks", String(totalChunks));
    formData.append("fileSize", String(file.size));

    const response = await fetch(
      `/api/uploads/${uploadId}/chunks`,
      {
        method: "POST",
        body: formData,
      }
    );

    if (!response.ok) {
      throw new Error(`Chunk ${index} failed to upload`);
    }

    uploadedBytes += chunk.size;

    const percentage = Math.round(
      (uploadedBytes / file.size) * 100
    );

    progressElement.value = percentage;

    statusElement.textContent =
      `Uploading ${file.name}: ${percentage}%`;
  }

  const completionResponse = await fetch(
    `/api/uploads/${uploadId}/complete`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileName: file.name,
        fileSize: file.size,
        totalChunks,
      }),
    }
  );

  if (!completionResponse.ok) {
    throw new Error("Could not complete the upload");
  }

  const result = await completionResponse.json();

  statusElement.textContent =
    `${result.fileName} uploaded successfully!`;
}

uploadButton.addEventListener("click", async () => {
  const file = fileInput.files[0];

  if (!file) {
    statusElement.textContent = "Please select a file first.";
    return;
  }

  if (file.size === 0) {
    statusElement.textContent = "Empty files are not supported.";
    return;
  }

  uploadButton.disabled = true;
  progressElement.value = 0;

  try {
    await uploadFile(file);
  } catch (error) {
    console.error(error);
    statusElement.textContent =
      `Upload failed: ${error.message}`;
  } finally {
    uploadButton.disabled = false;
  }
});

That's the basic frontend and backend flow.

Start the application:

node server.js

Open http://localhost:3000 in your browser, select a file, and click Upload File.

The browser divides the file into 5 MB chunks, uploads them one at a time, and asks the backend to assemble the file when all chunk requests succeed.

The example uses sequential uploads, which makes the implementation easier to understand and avoids multiple simultaneous chunk writes. It also provides a simple progress indicator.

One limitation is that the progress bar updates after each chunk finishes. If you need precise byte-level progress while an individual chunk is transferring, use XMLHttpRequest.upload.onprogress or another upload mechanism that exposes request-upload progress. Standard fetch() does not provide a broadly supported upload-progress event.

Step 8: Add Retry Logic for Failed Chunks

In a real application, a request may fail because of a temporary network issue or server timeout.

Instead of immediately abandoning the entire upload, we can retry a failed chunk.

Here's a reusable helper:

async function uploadChunkWithRetry(
  url,
  formData,
  maxAttempts = 3
) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const response = await fetch(url, {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        return await response.json();
      }

      // Retrying a bad request won't usually fix invalid metadata.
      if (response.status >= 400 && response.status < 500) {
        throw new Error(
          `Upload rejected with status ${response.status}`
        );
      }

      throw new Error(
        `Temporary upload failure: ${response.status}`
      );
    } catch (error) {
      if (attempt === maxAttempts) {
        throw error;
      }

      const delay = 1000 * 2 ** (attempt - 1);

      await new Promise((resolve) => {
        setTimeout(resolve, delay);
      });
    }
  }
}

This helper uses exponential backoff: it waits longer after each failed attempt.

For example:

Attempt 1 fails -> Wait 1 second
Attempt 2 fails -> Wait 2 seconds
Attempt 3 fails -> Stop and report the error

You can use this helper in the upload loop instead of calling fetch() directly for each chunk.

One implementation detail matters here: the FormData object can be reused for sequential retries like these because the request is reconstructed for each fetch() call. The server must also handle duplicate chunk submissions safely. Our example overwrites the same chunk index, making a retry idempotent when the same bytes are sent again.

For stronger guarantees, the backend should verify that a retried chunk matches the expected content, ideally using a checksum.

Also, don't retry every error indefinitely. Authentication failures, invalid metadata, quota errors, and other permanent failures should be reported rather than retried blindly.

Step 9: Make the Upload Resumable

We've already added an endpoint that returns uploaded chunk indexes. Now we can use it to skip chunks that are already present.

For example, after a connection drops, the client can request:

const response = await fetch(
  `/api/uploads/${uploadId}`
);

const { uploadedChunks } = await response.json();

const uploadedSet = new Set(uploadedChunks);

Inside the upload loop, skip chunks that have already arrived:

for (let index = 0; index < totalChunks; index++) {
  if (uploadedSet.has(index)) {
    continue;
  }

  // Create and upload this chunk.
}

This is only the core idea. To make it work across page refreshes, the client must retain the original upload ID and enough metadata to identify the same file and chunk configuration.

You should also persist server-side metadata such as the file size, chunk size, owner, upload status, and expiration time. The server must reject a resume request if the file or configuration differs from the original upload.

Don't generate a completely new upload ID when resuming. If you do, the server will treat the request as a new upload and won't find the previous chunks.

Step 10: Improve the Implementation for Production

The example above is enough to understand the core technique, but handling real user uploads requires more than splitting a file and joining its parts.

Here are the main areas I would address before deploying a chunked upload system.

1. Validate file types and contents

Don't trust the file extension or the MIME type supplied by the browser.

A user can rename a file or manipulate request metadata. Validate file types using an allowlist and, where appropriate, inspect file signatures or use a trusted file-detection library.

If users can upload images, documents, or videos, consider malware scanning and file-processing workflows before making the files available to other users.

2. Authenticate and authorize every request

A user should only be able to upload, inspect, resume, complete, or cancel their own uploads.

Associate each upload ID with an authenticated user. Validate ownership on every endpoint, and don't assume that a UUID makes an upload private.

You should also apply rate limits and quotas to prevent a user from creating thousands of incomplete uploads.

3. Store upload metadata

For a production application, a database can track upload state.

For example, a MongoDB document might look like this:

{
  uploadId: "generated-upload-uuid",
  userId: "authenticated-user-id",
  fileName: "demo-video.mp4",
  fileSize: 104857600,
  chunkSize: 5242880,
  totalChunks: 20,
  status: "uploading",
  createdAt: new Date(),
  expiresAt: new Date()
}

This is an illustrative record rather than a complete Mongoose schema. In a real implementation, define appropriate indexes, ownership rules, and expiration policies.

The upload status might transition through states such as:

uploading -> assembling -> completed
                    \-> failed

Persisting this information makes it easier to resume uploads, track failures, and clean up expired sessions.

4. Clean up abandoned uploads

Not every upload will finish.

Users may close their browsers, lose their connection, or abandon a form halfway through.

Without cleanup, temporary chunks will accumulate and consume disk space.

A scheduled cleanup job can remove expired uploads, but it should only delete data that is confirmed to be expired and not actively being assembled. In distributed systems, coordinate cleanup with upload workers to avoid deleting chunks that are still in use.

5. Handle concurrent requests safely

Our example uploads chunks sequentially, but many applications upload multiple chunks in parallel to improve throughput.

Parallel uploads can be useful, but they introduce additional concerns. The backend must safely handle duplicate requests, concurrent completion calls, and multiple workers accessing the same upload.

Use per-upload state management, locks or atomic state transitions where needed, and ensure that a file is assembled only once after all chunks have been verified.

6. Consider object storage for large files

If you're building an application that handles many large files, storing everything on your Node.js server may not be the best long-term choice.

Services such as Amazon S3 provide multipart upload functionality, allowing large files to be uploaded in parts and completed when the required parts have arrived.

For this architecture, the backend can authorize the upload and issue short-lived, scoped upload URLs. The browser uploads parts directly to object storage, and the backend verifies the upload state before completing it.

This reduces the amount of file data passing through your Node.js application and can simplify storage scaling.

However, direct-to-storage uploads still need authentication, authorization, part validation, storage quotas, and cleanup of incomplete multipart uploads.

Chunked Uploads vs. Normal File Uploads

Let's compare the two approaches.

Feature

Normal upload

Chunked upload

Upload method

One request for the entire file

Multiple requests for individual chunks

Large-file handling

Can be difficult with request and infrastructure limits

Allows bounded-size requests

Retry behavior

Often requires resending the file

Can retry individual chunks

Resume support

Requires additional implementation

Can be built around uploaded chunk state

Progress tracking

Possible, depending on the upload mechanism

Can track progress across chunks

Backend complexity

Generally simpler

Requires chunk tracking and assembly

Storage requirements

Usually stores the completed file

Often needs temporary storage for chunks

Best suited for

Small files and straightforward uploads

Large files and uploads that need resilience

There isn't a reason to use chunking for every upload. If your application only accepts small profile pictures, a normal multipart upload is likely sufficient.

But if you're building a video platform, a document-management system, a backup service, or an application where users regularly upload large datasets, chunking is worth considering.

Common Mistakes to Avoid

A few mistakes can make a chunked-upload implementation unreliable.

Using different chunk sizes on the frontend and backend: Both sides should follow the same upload configuration. Otherwise, size validation and chunk counts won't match.

Combining chunks in the wrong order: Always assemble chunks by their numeric index, not by the order in which the operating system returns file names.

Assuming every request will succeed: Network failures are normal. Implement bounded retries and a clear recovery path.

Trusting the original file name: Sanitize file names and generate unique server-side storage names. Never allow user-supplied paths to determine where files are written.

Ignoring temporary storage: Incomplete uploads can consume significant disk space. Track upload state and expire abandoned sessions.

Uploading too many chunks simultaneously: High concurrency can overload the server, storage service, or network. Start with sequential uploads and introduce a small, configurable concurrency limit only when it provides a measurable benefit.

Assuming chunking provides security: Chunking is a transfer technique, not a security feature. You still need authentication, authorization, validation, quotas, and safe storage policies.

Treating successful chunk requests as a completed upload: A file should only be marked complete after every expected chunk has been verified and assembly has succeeded.

Final Thoughts

Chunked uploading is a useful technique when your application needs to handle large files more reliably.

The basic idea is straightforward: divide the file into smaller pieces, upload each piece, store it temporarily, and combine the chunks in their original order. From there, you can build retries, resumable uploads, progress tracking, and better error handling.

In a Node.js application, Express and Multer are enough to demonstrate the core workflow. For production systems, you'll also need persistent upload metadata, user authorization, safe concurrent processing, temporary-file cleanup, and appropriate storage infrastructure.

If your application handles only small files, keep the implementation simple. But if users regularly upload large videos, archives, or datasets, chunked uploads can give you a much better foundation for a reliable file-upload system.

The most important thing to remember is that a reliable upload system isn't just about splitting a file into chunks. It's about knowing which chunks arrived, recovering from failures, validating the completed file, and making sure users can trust the result.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘