File API

Note: This feature is available in Web Workers.

Concepts and Usage

The File API enables web applications to access files and their contents.

Web applications can access files when the user makes them available, either using a file <input> element or via drag and drop.

Sets of files made available in this way are represented as FileList objects, which enable a web application to retrieve individual File objects. In turn File objects provide access to metadata such as the file's name, size, type, and last modified date.

File objects can be passed to FileReader objects to access the contents of the file. The FileReader interface is asynchronous, but a synchronous version, available only in web workers, is provided by the FileReaderSync interface.

Interfaces

Blob

Represents a "Binary Large Object", meaning a file-like object of immutable, raw data; a Blob can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.

File

Provides information about a file and allows JavaScript in a web page to access its content.

FileList

Returned by the files property of the HTML <input> element; this lets you access the list of files selected with the <input type="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage.

FileReader

Enables web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

FileReaderSync

Enables web applications to synchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

Extensions to other interfaces

URL.createObjectURL()

Creates a URL that can be used to fetch a File or Blob object.

URL.revokeObjectURL()

Releases an existing object URL which was previously created by calling URL.createObjectURL().

Examples

Reading a file

In this example, we provide a file <input> element, and when the user selects a file, we read the contents of the first file selected as text, and display the result in a <div>.

HTML

html
<input type="file" />
<div class="output"></div>

CSS

css
.output {
  overflow: scroll;
  margin: 1rem 0;
  height: 200px;
}

JavaScript

js
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");

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

  if (file) {
    output.innerText = await file.text();
  }
});

Result

Specifications

Specification
File API

See also