Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: File Transfer With Progress and Checksum

Build a peer-to-peer file sender: a metadata header, 16 KiB chunks with backpressure, progress reporting, reassembly into a Blob and SHA-256 verification, all runnable in one page.

File sharing is the classic data channel project: no upload to a server, no size limit except what the two browsers can handle, and the bytes are encrypted end to end between the peers. In this project you will build the whole pipeline in about 100 lines: describe the file, send it in chunks with backpressure, report progress, rebuild it on the other side, and verify that it arrived bit for bit using a SHA-256 checksum.

You will use what you learned in Binary Data and Backpressure and Protocols and Patterns. The "file" here is generated in memory (a sandboxed preview cannot open local files), but the code works the same with a real File from an <input type="file">, as shown at the end.

The protocol

The transfer uses one reliable, ordered channel. Order matters because chunks are appended in arrival order. The messages:

  1. Header (JSON string): { "type": "file", "name": "...", "size": N, "mime": "...", "sha256": "..." }
  2. Chunks (binary): each an ArrayBuffer of up to 16 KiB.
  3. Done (JSON string): { "type": "done" }
sequenceDiagram
  participant S as Sender
  participant R as Receiver
  S->>R: header (name, size, sha256)
  loop until all bytes sent
    S->>R: chunk (16 KiB, binary)
    Note over S: pause when bufferedAmount is high
  end
  S->>R: done
  R->>R: join chunks into a Blob, hash it, compare

Text messages describe the file; binary messages carry its content.

The receiver can tell the two kinds apart by type: strings are control messages, ArrayBuffers are data.

Hashing with WebCrypto

crypto.subtle.digest('SHA-256', buffer) returns an ArrayBuffer hash. A helper converts it to hex:

JavaScript
async function sha256Hex(buffer) {
  const hash = await crypto.subtle.digest('SHA-256', buffer);
  return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

The sender computes the hash up front and puts it in the header. The receiver computes the hash of what it received and compares. A mismatch means data was lost, reordered or tampered with, and the app should say so and offer a retry.

The working project

The program below sends a 300,000-byte generated file (bytes follow a repeating i % 251 pattern). Its SHA-256 was computed independently with Node's crypto module and is stored as EXPECTED, so you can also see the helper agrees with a second implementation.

JS Send a file and verify its checksum

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The checksum travels in the header, which is fine on the same encrypted channel, but it proves integrity rather than who sent it. Pair it with a trusted signalling channel when identity matters.

Using a real file

In a normal page, replace the generated Blob with the user's file. Everything else stays the same, because File extends Blob:

HTML
<input type="file" id="picker">
<script>
  document.getElementById('picker').addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) sendFile(channel, file, file.name);
  });
</script>

On the receiving side, show a download link with URL.createObjectURL(blob) and the original name in the download attribute. Revoke the URL with URL.revokeObjectURL when you are done.

Two details change for huge files. Hashing with blob.arrayBuffer() loads everything into memory, so for multi-gigabyte files hash incrementally in a Worker (WebCrypto's digest is one-shot; use a streaming hash library). And on the receiving side, writing chunks directly to disk with the File System Access API's FileSystemWritableFileStream (where available) avoids holding the whole file in memory.

Hardening checklist

  • Sanitize the file name. Remove path separators and control characters; never trust the sender's name.
  • Limit the size. Reject a header whose size is larger than you accept.
  • Count bytes. If more data arrives than size says, abort.
  • Ask the user. Show "Ben wants to send photo.jpg (2.1 MB). Accept?" before saving.
  • Timeouts and cancel. Let either side cancel; send a { type: "cancel" } message and clear state.
  • Resume support: number chunks and let the receiver request missing ranges after a reconnect.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why send the file header as a JSON string and chunks as binary?

    A channel can carry both. Checking typeof data tells the receiver which is which.
  2. 2. What problem does comparing SHA-256 hashes solve?

    If the hash of the received bytes differs from the announced hash, the file is not identical to the original.
  3. 3. Why does the sender pause when bufferedAmount is large?

    Backpressure keeps the queue small by resuming only when bufferedamountlow fires.
  4. 4. Which receiver safeguard prevents a hostile sender from exhausting memory?

    Never trust peer-supplied sizes without enforcing them.

Summary

  • A transfer is: header, chunks with backpressure, done, then verification.
  • Use Blob.slice() to read lazily and 16 KiB chunks for compatibility.
  • SHA-256 via crypto.subtle.digest proves the bytes match.
  • Sanitize names, enforce size limits, ask for consent and support cancel.

Next: Project: A Signalling Server and Room Join