Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 122 ยท Web APIs

Files, File Uploads and the FileReader API

Let users pick files with input type=file, read them with File, Blob and FileReader, preview images with object URLs and send uploads with FormData.

Sooner or later every web app needs files: a profile photo, a CSV to import, a PDF to attach to a support ticket. HTML gives you one element for this, <input type="file">, and JavaScript gives you a small family of objects (File, Blob, FileReader, URL.createObjectURL) that let you look inside a chosen file before anything is sent to a server.

This lesson covers the whole path: choosing files, restricting what can be chosen, reading text and images locally, previewing them, and finally uploading them. The key idea is that the browser reads a file from the user's disk only after the user picks it, and only the file or files they picked. Your page never sees a folder listing or a full path.

The live examples run in a sandboxed preview, so they create their own sample files with new File(...) instead of asking you to browse your disk. The code that reads those files is exactly the code you would use with a file chosen from the picker.

The file input

A file input renders a button and a label that shows the chosen file name.

HTML
<label for="avatar">Profile picture</label>
<input type="file" id="avatar" name="avatar" accept="image/*">

Three attributes shape the picker:

Attribute Effect
accept Hint about allowed types: a list of extensions (.pdf,.docx), MIME types (image/png) or wildcards (image/*, audio/*, video/*).
multiple Lets the user select more than one file.
capture On phones, asks for the camera or microphone directly (capture="environment" for the rear camera). It is a hint, and desktop browsers ignore it.

accept only filters the picker. A user can still choose "All files", rename a file, or send a request without your form at all, so it is a convenience, never a security check. Always validate type and size again on the server.

Two more things to know. A form that contains a file input must use method="post" and enctype="multipart/form-data" to upload files in the normal way (see Form Attributes). And for security, you cannot set the value of a file input from script: input.value = "report.pdf" throws an error. Only the user can choose a file.

The File and Blob objects

When the user picks files, the input's files property holds a FileList, an array-like list of File objects. Each File is a special Blob (a chunk of raw data with a size and a type) that also has a name and a lastModified timestamp.

Inspect File objects

The same three properties, name, type and size, are what you check before accepting a file. type comes from the file extension according to the operating system, which means it can be empty or wrong. Treat it as a first filter only.

Validating before you upload

A client-side check gives the user instant feedback and saves a pointless upload. Compare the size and type to your limits:

JavaScript
const MAX_BYTES = 2 * 1024 * 1024; // 2 MB
const ALLOWED = ["image/png", "image/jpeg", "image/webp"];

function checkFile(file) {
  if (!ALLOWED.includes(file.type)) return "Please choose a PNG, JPEG or WebP image.";
  if (file.size > MAX_BYTES) return "That file is larger than 2 MB.";
  return ""; // empty string means OK
}

Hook it to the input's change event, which fires when the user finishes picking:

JavaScript
input.addEventListener("change", () => {
  const message = checkFile(input.files[0]);
  input.setCustomValidity(message); // shows in the form's validation UI
  input.reportValidity();
});

setCustomValidity() plugs your message into the built-in form validation you met in Form Validation.

Reading a file with FileReader

FileReader reads the contents of a Blob or File asynchronously. You create one, attach a load handler, and call one of its read methods:

Method Result
readAsText(file) A string, decoded as UTF-8 unless you pass another encoding
readAsDataURL(file) A data: URL string, usable as an image src
readAsArrayBuffer(file) Raw bytes in an ArrayBuffer
Read a CSV file as text

The read is asynchronous so large files do not freeze the page. You can also listen for progress events (with event.loaded and event.total) to drive a progress bar, and abort() to cancel.

The promise-based shortcut

Modern browsers also let you call methods straight on the file, no FileReader needed:

JavaScript
const text = await file.text();               // string
const buffer = await file.arrayBuffer();      // ArrayBuffer
const stream = file.stream();                 // ReadableStream for huge files

Use these in new code when you just need the contents. FileReader is still useful for readAsDataURL and for progress events.

Previewing images with object URLs

To show a chosen image you do not need to read it into memory at all. URL.createObjectURL(file) makes a short blob: URL that points to the file, and you can put it in an <img>. It is much cheaper than a data URL for big pictures.

Preview an image with an object URL

Notice URL.revokeObjectURL(). An object URL keeps its file alive until the page closes or you revoke it. Revoke it when you replace or remove the preview, otherwise a long session can leak memory.

Drag and drop onto a drop zone

A friendlier upload control accepts dropped files. This builds on Drag and Drop: cancel dragover so the element accepts drops, then read event.dataTransfer.files in the drop handler.

HTML
<div id="zone" tabindex="0">Drop files here</div>

<script>
  const zone = document.getElementById("zone");

  zone.addEventListener("dragover", (event) => event.preventDefault());
  zone.addEventListener("drop", (event) => {
    event.preventDefault();
    for (const file of event.dataTransfer.files) {
      console.log(file.name, file.size);
    }
  });
</script>

Always keep the real <input type="file"> available as well. Keyboard and screen reader users cannot drag, and a visible button is the accessible way to choose files.

Uploading with FormData and fetch

To send files to a server, put them in a FormData object and post it with fetch. Do not set the Content-Type header yourself: the browser adds the correct multipart/form-data header, including the boundary string.

JavaScript
const data = new FormData();
data.append("title", "Holiday photo");
data.append("photo", input.files[0]);        // the File itself

const response = await fetch("/upload", { method: "POST", body: data });
if (!response.ok) throw new Error("Upload failed: " + response.status);

Or build it straight from a form: new FormData(formElement) collects every field, including file inputs.

fetch cannot report upload progress. If you need a progress bar for large uploads, use XMLHttpRequest and its upload.onprogress event, or split the file with file.slice(start, end) and upload it in chunks.

Server-side reminders

Whatever your language, treat uploads as hostile input: check size and real content type on the server, generate your own file names instead of trusting file.name, store files outside the public web root (or in object storage), and never execute anything uploaded.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which object does an <input type="file"> expose to JavaScript after the user picks files?

    input.files is a FileList of File objects. The browser never exposes the full disk path.
  2. 2. Why should you still validate uploads on the server when you use the accept attribute?

    accept filters what the picker shows, but users can pick any file or send requests without your page, so the server must check type and size.
  3. 3. What is the main benefit of URL.createObjectURL() for previewing an image?

    An object URL is a cheap reference to the file. Revoke it when you no longer need it so the browser can release the memory.
  4. 4. When posting a FormData object with fetch, what should you do about the Content-Type header?

    The boundary string is generated by the browser. If you set the header yourself the boundary is missing and the server cannot parse the body.

Summary

  • <input type="file"> lets users choose files; accept, multiple and capture shape the picker but are not security checks.
  • Chosen files arrive as File objects (a kind of Blob) with name, type, size and lastModified.
  • Read contents with file.text() / arrayBuffer() or with FileReader (readAsText, readAsDataURL, progress events).
  • Preview images with URL.createObjectURL() and release them with URL.revokeObjectURL().
  • Drop zones read event.dataTransfer.files, but keep the normal input for keyboard users.
  • Upload with FormData and fetch, never setting the multipart header yourself, and validate everything again on the server.

Next lesson: Web Storage, where you save small pieces of data in the browser.