This is the 19th day of my participation in the Genwen Challenge


The ability to select and interact with files on a user’s local device is one of the most common features of the Web. Previously, you could only do this after uploading the file in its entirety. Until the File System Access API came along.

What is the File System Access API

The File System Access API allows users to select files and upload them to the server, such as uploading photos. However, it also allows websites to read and manipulate them without transferring data across the entire network.

Please note that a search may turn up something called the File System API, which is no longer recommended. The new proposal can be seen at WICG, updated at 2021.6.4.

For details on the proposal, see the File System Access API

What can it do?

  • The application can interact with files on the user’s local device
  • Read and write files and create folders without uploading the entire file
  • You can open the directory and list the contents

Browser support

  • Google Browser support, Chromium kernel based browser support.
  • For unsupported browsers, you can use browser-fs-access to polyfill

The sample

There is an example text editor, source code on Github. This example gives you an overview of how the File System Access API is used.

How to do

preparation

First, the File System Access API only allows calls in secure environments. How to use HTTPS in your local development environment Some API calls need to be triggered manually by users.

Open a file

Call window. ShowOpenFilePicker () method, which can open the file selection dialog box to choose a single file, similar to the picture below this:

Option window. ShowOpenFilePicker method supports incoming optional parameters, these parameters can affect the file selection dialog box, such as the specified file type, can be multiple files and so on.

This method call needs to be triggered manually by the user

let fileHandle;
butOpenFile.addEventListener('click'.async() = > {// Destructure the one-element array.
  [fileHandle] = await window.showOpenFilePicker();
  // Do something with the file handle.
});
Copy the code

After the file is selected, the API returns a set of file operations, Called Handles, that contain properties and methods needed to interact with the file, such as reading and writing files.

Reads a file from the file system

In the previous step you got the file operation Handle, which allows you to get file properties or access the file itself.

Now, I just need to read the contents of the file. Call the getFile method to get the file object, which contains a BLOB. To read bloB data, you can use one of the following methods: stream(), text(), arrayBuffer(), slice().

const file = await fileHandle.getFile();
const contents = await file.text();
Copy the code