--- title: Введение в API файлов и каталогов slug: Web/API/File_and_Directory_Entries_API/Introduction translation_of: Web/API/File_and_Directory_Entries_API/Introduction original_slug: Web/API/File_and_Directory_Entries_API/Введение ---
API файлов и каталогов эмулирует для веб-приложений локальную файловую систему. У вас есть возможность создания приложений, которые могут читать, записывать и создавать файлы и директории в изолированной виртуальной файловой системе.
API файлов и каталогов взаимодействует с другими API. Оно было создано на основе File Writer API, который в свою очередь использует File API. Каждое API реализует разную функциональность. Данные программные интерфейсы являются огромным эволюционным скачком для веб-приложений, которые теперь могут кешировать и обрабатывать большие объёмы данных.
В данном документе приведены основные концепции и терминология API файлов и каталогов, которые должны показать общую картину и ключевые идеи. Также описаны ограничения, несоблюдение которых может привести к появлению ошибок безопасности. Используемая терминология описана в разделе Определений.
Ссылки на страницы данного API приведены в Ссылочном справочнике.
Спецификация находится на стадии разработки и будет изменяться в будущем.
Программный интерфейс файлов и каталогов включает асинхронные и синхронные методы. Асинхронное API может быть использовано в тех случаях, когда нежелательно, чтобы длительные вычисления блокировали весь пользовательский интерфейс. В свою очередь синхронное API предлагает более простую модель программирования, однако оно должно использоваться только с объектами WebWorkers.
API файлов и каталогов является важным программным интерфейсом по следующим причинам:
Примеры таких приложений приведены в разделе Примеры использования.
API файлов и каталогов является альтернативой для других интерфейсов хранения данных, таких как IndexedDB, WebSQL (признано устаревшим с 18 ноября 2010 г.) и AppCache. Тем не менее данное API является более хорошим выбором для приложений, обрабатывающим большие объёмы данных, по следующим причинам:
Далее приведены лишь некоторые случаи, в которых можно использовать API файлов и каталогов:
Before you start using the File and Directory Entries API, you need to understand a few concepts:
The API doesn't give you access to the local file system, nor is the sandbox really a section of the file system. Instead, it is a virtualized file system that looks like a full-fledged file system to the web app. It does not necessarily have a relationship to the local file system outside the browser.
What this means is that a web app and a desktop app cannot share the same file at the same time. The API does not let your web app reach outside the browser to files that desktop apps can also work on. You can, however, export a file from a web app to a desktop app. For example, you can use the File API, create a blob, redirect an iframe to the blob, and invoke the download manager.
An application can request temporary or persistent storage. Temporary storage is easier to get, because the browser just gives it to you, but it is limited and can be deleted by the browser when it runs out of space. Persistent storage, on the other hand, might offer you larger space that can only be deleted by the user, but it requires the user to grant you permission.
Use temporary storage for caching and persistent storage for data that you want your app to keep—such as user-generated or unique data.
To prevent a web app from using up the entire disk, browsers might impose a quota for each app and allocate storage among web apps.
How storage space is granted or allocated and how you can manage storage are idiosyncratic to the browser, so you need to check the respective documentation of the browser. Google Chrome, for example, allows temporary storage beyond the 5 MB required in the specifications and supports the Quota Management API. To learn more about the Chrome-specific implementation, see Managing HTML5 Offline Storage.
The File and Directory Entries API comes with asynchronous and synchronous versions. Both versions of the API offer the same capabilities and features. In fact, they are almost alike, except for a few differences.
requestFileSystem()
and resolveLocalFileSystemURL()
. These methods are members of both the window object and the worker global scope. The synchronous API, on the other hand, uses the following methods: requestFileSystemSync()
and resolveLocalFileSystemSyncURL()
. These synchronous methods are members of the worker's global scope only, not the window object.The synchronous API can be simpler for some tasks. Its direct, in-order programming model can make code easier to read. The drawback of synchronous API has to do with its interactions with Web Workers, which has some limitations.
When using the asynchronous API, always use the error callbacks. Although the error callbacks for the methods are optional parameters, they are not optional for your sanity. You want to know why your calls failed. At minimum, handle the errors to provide error messages, so you'll have an idea of what's going on.
The File and Directory Entries API is designed to be used with other APIs and elements on the web platform. For example, you are likely to use one of the following:
send()
method for file and blob objects)input
element (to programmatically obtain a list of files from the element)
For security reasons, browsers impose restrictions on file access. If you ignore them, you will get security errors.
An origin is the domain, application layer protocol, and port of a URL of the document where the script is being executed. Each origin has its own associated set of file systems.
The security boundary imposed on file system prevents applications from accessing data with a different origin. This protects private data by preventing access and deletion. For example, while an app or a page in http://www.example.com/app/ can access files from http://www.example.com/dir/, because they have the same origin, it cannot retrieve files from http://www.example.com:8080/dir/ (different port) or https://www.example.com/dir/ (different protocol).
To prevent malicious apps from running hostile executables, you cannot create executable files within the sandbox of the File and Directory Entries API.
Because the file system is sandboxed, a web app cannot access another app's files. You also cannot read or write files to an arbitrary folder (for example, My Pictures and My Documents) on the user's hard drive.
You cannot run your app locally from file://
. If you do so, the browser throws errors or your app fails silently. This restriction also applies to many of the file APIs, including BlobBuilder and FileReader.
For testing purposes, you can bypass the restriction on Chrome by starting the browser with the --allow-file-access-from-files
flag. Use this flag only for this purpose.
This section defines and explains terms used in the File and Directory Entries API.
Specification | Status | Comment |
---|---|---|
{{SpecName('File System API')}} | {{Spec2('File System API')}} | Draft of proposed API |
This API has no official W3C or WHATWG specification.
FileSystem
{{Compat}}
FileSystemSync
property{{Compat("api.FileSystemSync", 0)}}