Skip to content

File API

This lesson explains File API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 File API Overview

The HTML5 File API allows web applications to access, read, preview, validate, and process files selected by users without uploading them to a server immediately. It works together with the <input type="file"> element and the Drag and Drop API, enabling powerful browser-based applications.

The File API is widely used for image previews, document uploads, CSV readers, PDF viewers, video previews, drag-and-drop uploads, spreadsheet processing, file validation, and browser-based editors.

Feature Description
API Name HTML5 File API
Main Objects File, FileList, FileReader, Blob
Purpose Read and process local files.
Works With File Input, Drag and Drop API
Supported Files Images, PDFs, Videos, Audio, CSV, JSON, ZIP, Documents
Common Uses Upload, Preview, Validate, Parse, Export

File API Components

Object Description Common Methods / Properties
File Represents a single selected file. name, size, type, lastModified
FileList Collection of selected files. length, item()
FileReader Reads file contents. readAsText(), readAsDataURL()
Blob Represents binary data. slice(), stream()
URL Creates temporary object URLs. createObjectURL()

Select a File

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

<script>
const input =
  document.querySelector("#fileInput");

input.addEventListener("change", (event) => {
  const file =
    event.target.files[0];

  console.log(file.name);
  console.log(file.size);
  console.log(file.type);
});
</script>

When the user selects a file, the browser creates a File object containing metadata about that file.

File Object Properties

Property Description Example Value
name File name photo.jpg
size Size in bytes 1054218
type MIME type image/jpeg
lastModified Last modified timestamp 1714651000000
webkitRelativePath Relative folder path Documents/photo.jpg

Read Text File

const reader =
  new FileReader();

reader.onload = () => {
  console.log(reader.result);
};

reader.readAsText(file);

readAsText() is commonly used for CSV, TXT, XML, HTML, and JSON files.

Preview an Image

<input
  type="file"
  accept="image/*"
  id="imageInput">

<img id="preview">

<script>
const imageInput =
  document.querySelector("#imageInput");

const preview =
  document.querySelector("#preview");

imageInput.addEventListener("change", (event) => {
  const file =
    event.target.files[0];

  const reader =
    new FileReader();

  reader.onload = () => {
    preview.src =
      reader.result;
  };

  reader.readAsDataURL(file);
});
</script>

readAsDataURL() converts a file into a Base64 URL that can be displayed directly in an image element.

Preview Using Object URLs

const url =
  URL.createObjectURL(file);

preview.src = url;

// Later

URL.revokeObjectURL(url);

Object URLs are faster than Base64 for large files because they avoid loading the entire file into memory as encoded text.

Multiple File Upload Example

<input
  type="file"
  multiple
  id="files">

<script>
const files =
  document.querySelector("#files");

files.addEventListener("change", (event) => {

  Array.from(event.target.files)
    .forEach((file) => {

      console.log(file.name);

    });

});
</script>

Validate File Type and Size

const maxSize =
  5 * 1024 * 1024;

if (!file.type.startsWith("image/")) {
  console.log("Only images allowed.");
}

if (file.size > maxSize) {
  console.log("File exceeds 5 MB.");
}

Always validate files both in the browser and on the server because client-side validation alone is not secure.

Read Files from Drag and Drop

dropZone.addEventListener("drop", (event) => {

  event.preventDefault();

  const files =
    event.dataTransfer.files;

  Array.from(files)
    .forEach((file) => {

      console.log(file.name);

    });

});

The Drag and Drop API provides a FileList identical to the one returned by a file input element.

FileReader Methods

Method Returns Common Use
readAsText() String CSV, JSON, TXT
readAsDataURL() Base64 URL Image preview
readAsArrayBuffer() Binary Buffer PDF, ZIP, Images
readAsBinaryString() Binary String Legacy applications
abort() Stops reading Cancel large reads

FileReader Events

Event Description
loadstart Reading begins.
progress Reports reading progress.
load Reading completed successfully.
error Error occurred.
abort Reading cancelled.
loadend Reading finished.

Common File API Use Cases

  • Image preview before upload
  • PDF preview
  • CSV and Excel import
  • Video preview
  • Audio players
  • Document editors
  • Drag-and-drop uploads
  • Offline data processing

File API Best Practices

  • Validate file type and size before upload.
  • Always validate files again on the server.
  • Use Object URLs for large image previews.
  • Release Object URLs using URL.revokeObjectURL().
  • Display upload progress for large files.
  • Handle FileReader errors gracefully.
  • Restrict accepted file types using the accept attribute.
  • Provide keyboard-accessible upload controls.

Common File API Mistakes

  • Trusting client-side validation alone.
  • Loading extremely large files into memory.
  • Not revoking Object URLs.
  • Ignoring FileReader errors.
  • Using Base64 previews for very large media files.
  • Not limiting accepted MIME types.
  • Uploading files immediately without confirmation.
  • Not showing upload progress or validation feedback.

File vs Blob

Feature File Blob
Represents User-selected file Binary data
Has File Name ✔ Yes ✘ No
Has lastModified ✔ Yes ✘ No
Can Be Uploaded ✔ Yes ✔ Yes
Can Be Created in JavaScript Limited ✔ Yes

Key Takeaways

  • The File API enables browser-based file handling without immediate uploads.
  • Use FileReader to read local files.
  • Use Object URLs for efficient previews.
  • Validate every file before processing.
  • Combine the File API with Fetch, Blob, and Drag and Drop for complete upload workflows.
  • Always provide secure server-side validation.

Pro Tip

Modern upload systems combine the File API, Drag and Drop API, FormData, Fetch API, Object URLs, and image compression to create fast, responsive, and user-friendly upload experiences while minimizing memory usage and network bandwidth.