未验证 提交 232ab984 编写于 作者: O openharmony_ci 提交者: Gitee

!22310 [翻译完成】PR21934

Merge pull request !22310 from Annie_wang/PR21934
# File Management # File Management
- [File Management Overview](file-management-overview.md) - [File Management Overview](file-management-overview.md)
- Application File - Application Files
- [Application File Overview](app-file-overview.md) - [Application File Overview](app-file-overview.md)
- [Application Sandbox Directory](app-sandbox-directory.md) - [Application Sandbox Directory](app-sandbox-directory.md)
- Application File Access and Management - Application File Access and Management
- [Accessing Application Files](app-file-access.md) - [Accessing Application Files](app-file-access.md)
- [Uploading and Downloading Application Files](app-file-upload-download.md) - [Uploading and Downloading Application Files](app-file-upload-download.md)
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md) - [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md) - [Pushing Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md) - [Sharing an Application File](share-app-file.md)
- Application Data Backup and Restoration - Application Data Backup and Restoration
- [Application Data Backup and Restoration Overview](app-file-backup-overview.md) - [Application Data Backup and Restoration Overview](app-file-backup-overview.md)
- [Backing Up and Restoring Application Access Data](app-file-backup-extension.md) - [Backup and Restoration Accessed by Applications](app-file-backup-extension.md)
- [Backing Up and Restoring Application-triggered Data (for System Applications Only)](app-file-backup.md) - [Backup and Restoration Triggered by System Applications](app-file-backup.md)
- User File - User Files
- [User File Overview](user-file-overview.md) - [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker) - Selecting and Saving User Files (FilePicker)
- [Selecting User Files](select-user-file.md) - [Selecting User Files](select-user-file.md)
- [Saving User Files](save-user-file.md) - [Saving User Files](save-user-file.md)
- Album Management (photoAccessHelper) - Album Management (photoAccessHelper)
- [photoAccessHelper Overview](photoAccessHelper-overview.md) - [photoAccessHelper Overview](photoAccessHelper-overview.md)
- [Media Asset (Image and video) Management](photoAccessHelper-resource-guidelines.md) - [Managing Media Assets (Images and Videos)](photoAccessHelper-resource-guidelines.md)
- [User Album Management](photoAccessHelper-userAlbum-guidelines.md) - [Managing User Albums](photoAccessHelper-userAlbum-guidelines.md)
- [System Album Management](photoAccessHelper-systemAlbum-guidelines.md) - [Managing System Albums](photoAccessHelper-systemAlbum-guidelines.md)
- [Media Asset Change Notification Management](photoAccessHelper-notify-guidelines.md) - [Managing Media Asset Change Notifications](photoAccessHelper-notify-guidelines.md)
- [Developing a FileManager Application (for System Applications Only)](dev-user-file-manager.md) - [Developing a File Manager Application (for System Applications Only)](dev-user-file-manager.md)
- [Managing External Storage Devices (for System Applications Only)](manage-external-storage.md) - [Managing External Storage Devices (for System Applications Only)](manage-external-storage.md)
- Distributed File System - Distributed File System
- [Distributed File System Overview](distributed-fs-overview.md) - [Distributed File System Overview](distributed-fs-overview.md)
......
# Accessing Application Files # Accessing Application Files
This topic describes how to view, create, read, write, delete, move, or copy a file in the application file directory and obtain the file information. This topic describes how to enable an application to view, create, read, write, delete, move, or copy an application and obtain file information.
## Available APIs ## Available APIs
You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement the application file access capabilities. The following table describes the APIs. You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to application files. The following table describes the APIs.
**Table 1** APIs for basic application file operations **Table 1** APIs for basic application file operations
| API| Description| Type| Synchronous Programming| Asynchronous Programming| | API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| access | Checks whether a file exists.| Method| √ | √ | | access | Checks whether a file exists.| Method| √ | √ |
| close | Closes a file.| Method| √ | √ | | close | Closes a file.| Method| √ | √ |
| copyFile | Copies a file.| Method| √ | √ | | copyFile | Copies a file.| Method| √ | √ |
| createStream | Creates a stream based on the specified file path.| Method| √ | √ | | createStream | Creates a stream based on the specified file path.| Method| √ | √ |
| listFile | Lists all files in a directory.| Method| √ | √ | | listFile | Lists all files in a directory.| Method| √ | √ |
| mkdir | Creates a directory.| Method| √ | √ | | mkdir | Creates a directory.| Method| √ | √ |
| moveFile | Moves a file.| Method| √ | √ | | moveFile | Moves a file.| Method| √ | √ |
| open | Opens a file.| Method| √ | √ | | open | Opens a file.| Method| √ | √ |
| read | Reads data from a file.| Method| √ | √ | | read | Reads data from a file.| Method| √ | √ |
| rename | Renames a file or folder.| Method| √ | √ | | rename | Renames a file or folder.| Method| √ | √ |
| rmdir | Deletes a directory.| Method| √ | √ | | rmdir | Deletes a directory.| Method| √ | √ |
| stat | Obtains detailed file information.| Method| √ | √ | | stat | Obtains detailed file information.| Method| √ | √ |
| unlink | Deletes a single file.| Method| √ | √ | | unlink | Deletes a single file.| Method| √ | √ |
| write | Writes data to a file.| Method| √ | √ | | write | Writes data to a file.| Method| √ | √ |
| Stream.close | Closes a stream.| Method| √ | √ | | Stream.close | Closes a stream.| Method| √ | √ |
| Stream.flush | Flushes all data from this stream.| Method| √ | √ | | Stream.flush | Flushes all data from this stream.| Method| √ | √ |
| Stream.write | Writes data to a stream.| Method| √ | √ | | Stream.write | Writes data to a stream.| Method| √ | √ |
| Stream.read | Reads data from a stream.| Method| √ | √ | | Stream.read | Reads data from a stream.| Method| √ | √ |
| File.fd | Defines a file descriptor.| Attribute| √ | × | | File.fd | Defines a file descriptor.| Attribute| √ | × |
| OpenMode | Defines the mode for opening a file.| Attribute| √ | × | | OpenMode | Defines the mode for opening a file.| Attribute| √ | × |
| Filter | Defines the options for setting the file filter.| Type| × | × | | Filter | Defines the options for setting the file filter.| Type| × | × |
## Development Example ## Development Example
Obtain the [application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). First, obtain the [application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). The following example shows how to obtain a HAP file path using **UIAbilityContext**. For details about how to obtain **UIAbilityContext**, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
The following describes common file operations. Then, perform common file operations.
### Creating, Reading, and Writing a File ### Creating, Reading, and Writing a File
...@@ -68,8 +68,8 @@ function createFile() { ...@@ -68,8 +68,8 @@ function createFile() {
### Copying Data to Another File ### Copying Data to Another File
The following example demonstrates how to write the data read from a file to another file. The following example demonstrates how to read data from a file and write it to another file.
```ts ```ts
// pages/xxx.ets // pages/xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
...@@ -101,12 +101,12 @@ function readWriteFile() { ...@@ -101,12 +101,12 @@ function readWriteFile() {
> **NOTE** > **NOTE**
> >
> When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, the offset pointer is at the end position of the last read or write operation by default. > When using **read()** or **write()**, pay attention to the optional parameter **offset**. For a file that has been read or written, **offset** points to the end position of the last read or write operation by default.
### Reading and Writing Files in a Stream ### Reading and Writing Files in a Stream
The following example demonstrates how to read and write file data using a stream. The following example demonstrates how to read and write file data using a stream.
```ts ```ts
// pages/xxx.ets // pages/xxx.ets
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
...@@ -138,12 +138,14 @@ async function readWriteFileWithStream() { ...@@ -138,12 +138,14 @@ async function readWriteFileWithStream() {
``` ```
> **NOTE** > **NOTE**
> >
> Close the stream that is no longer used in a timely manner. <br>Comply with the related programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode. <br>The **Stream** APIs do not support concurrent read and write operations. > - Close the stream that is no longer used in a timely manner.
> - Comply with the programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode.
> - The **Stream** APIs do not support concurrent read and write operations.
### Listing Files ### Listing Files
The following example demonstrates how to list files. The following example demonstrates how to list files that meet the specified conditions.
```ts ```ts
// List files. // List files.
...@@ -162,7 +164,7 @@ let options = { ...@@ -162,7 +164,7 @@ let options = {
suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'. suffix: ['.png', '.jpg', '.txt'], // The filename extension can be '.png', '.jpg', or '.txt'.
displayName: ['test%'], // The filename starts with 'test'. displayName: ['test%'], // The filename starts with 'test'.
fileSizeOver: 0, // The file size is greater than or equal to 0. fileSizeOver: 0, // The file size is greater than or equal to 0.
lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970. lastModifiedAfter: new Date(0).getTime(), // The latest modification time of the file is later than January 1, 1970.
}, },
} }
let files = fs.listFileSync(filesDir, options); let files = fs.listFileSync(filesDir, options);
......
# Backing Up and Restoring Application Access Data # Backup and Restoration Accessed by Applications
You can use BackupExtensionAbility to implement backup and restoration of application access data. You can use BackupExtensionAbility to enable an application to access the backup and restoration framework.
BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the behavior of the backup and restoration framework, including whether backup and restoration are allowed and which files are backed up. BackupExtensionAbility is a class derived from the [ExtensionAbility](../application-models/extensionability-overview.md) component in [Stage Model](../../application-dev/application-models/stage-model-development-overview.md). You can modify the configuration file to customize the backup and restoration framework behavior, including whether to allow backup and restoration and specifying the files to be backed up.
## Constraints ## Constraints
- The paths of all files and directories to be backed up cannot exceed 4095 bytes. Otherwise, undefined behavior may occur. - The paths of all files and directories to be backed up cannot exceed 4095 bytes. Otherwise, undefined behavior may occur.
- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails. - If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails.
- If a file needs to be backed up, the application process must have the permission to search for its grandparent directory of the file (**x** in DAC). Otherwise, the backup fails. - If a file needs to be backed up, the application process must have the permission to retrieve the grandparent directory of the file (**x** in DAC). Otherwise, the backup fails.
## How to Develop ## How to Develop
1. Add the **extensionAbilities** configuration in the application's **module.json5** file. 1. Add **extensionAbilities** to the application's **module.json5** file.
Add **extensionAbilities**, set **type** to **backup**, and add **name: ohos.extension.backup** to **[metadata]**(../../application-dev/reference/apis/js-apis-bundleManager-metadata.md). Add the **extensionAbilities** field, set **type** to **backup**, and add a record with **name** of **ohos. extension. backup** to **[metadata](../../application-dev/reference/apis/js-apis-bundleManager-metadata.md)**.
BackupExtensionAbility configuration example: BackupExtensionAbility configuration example:
...@@ -40,7 +40,7 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica ...@@ -40,7 +40,7 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
2. Add a metadata resource configuration file. 2. Add a metadata resource configuration file.
The metadata resource configuration file defines the files to be transferred during backup and restoration. The file name must be the same as the value of **resource** under **metadata** in the **module.json5** file. This file is stored in the **Profile** folder. The metadata resource configuration file defines the files to be transferred during the backup and restoration process. The file is located in the **Profile** folder, and the file name must be the same as the value of **resource** under **metadata** in the **module.json5** file.
Metadata resource configuration file example: Metadata resource configuration file example:
...@@ -61,8 +61,8 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica ...@@ -61,8 +61,8 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| allowToBackupRestore | Boolean | Yes | Whether to allow backup and restoration. The default value is **false**. | | allowToBackupRestore | Boolean | Yes | Whether to allow backup and restoration. The default value is **false**. |
| includes | String array| No | Files and directories to be backed up in the application sandbox.<br>Each item in the array is a pattern string, which can contain shell-style wildcards such as *****, **?**, and **[**.<br>The pattern string that does not start with a slash (/) indicates a relative path relative to the root path.<br>If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).| | includes | String array| No | Files and directories to be backed up in the application sandbox.<br>Each item in the array is a pattern string, which can contain shell-style wildcards such as (`*`, `?`, `[`).<br>The pattern string that does not start with a slash (/) indicates a relative path.<br>If **includes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses the **includes** default value (see the following code segment).|
| excludes | String array| No | Exception items in **includes** that do not need to be backed up. The value is in the same format as **includes**.<br>If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. | | excludes | String array| No | Items in **includes** that do not need to be backed up. The value is in the same format as **includes**.<br>If **excludes** is configured, the backup and restoration framework uses the pattern strings configured. Otherwise, the backup and restoration framework uses an empty array as the default value. |
**includes** default value: **includes** default value:
...@@ -77,4 +77,4 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica ...@@ -77,4 +77,4 @@ BackupExtensionAbility is a class derived from the [ExtensionAbility](../applica
"data/storage/el2/base/haps/*/preferences/", "data/storage/el2/base/haps/*/preferences/",
] ]
} }
``` ```
\ No newline at end of file
# Application Data Backup and Restoration Overview # Application Data Backup and Restoration Overview
Application data, such as the configuration and service data, is generated when an application is used. To ensure that user data will not be lost due to operations, such as application updates and hopping, applications need to access data backup and restoration. Application data, such as the configuration and service data, is generated when an application is used. To prevent user data against loss due to operations such as application updates and hopping, the application data needs to be backed up and restored.
Before development, you need to understand the ExtensionAbility component. For details, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md). Before development, you need to understand the [ExtensionAbility](../application-models/extensionability-overview.md) component.
BackupExtensionAbility is a class derived from ExtensionAbility in the stage model. It provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete. Derived from ExtensionAbility in the stage model, BackupExtensionAbility provides the capabilities of backing up and restoring application data. It is an extended component without the UI. It runs when a backup or restoration task starts and exits when the task is complete.
The implementation includes the following: The implementation includes the following:
- [Backup and restoration of application access data](app-file-backup-extension.md): All applications can access data backup and restoration. After accessed, the application can modify the configuration file to customize the behavior of the backup and restoration framework, including whether to allow backup and restoration and specifying the data to be backed up. - [Backup and restoration accessed by applications](app-file-backup-extension.md): All applications can access the data backup and restoration framework. You can customize the backup and restoration framework behavior for the application, including whether to allow backup and restoration and specifying the data to be backed up, by modifying the application configuration file.
Applications can perform backup and restoration configurations, but not trigger data backup and restoration. The application itself cannot trigger data backup and restoration.
- [Backup and restoration of application-triggered data](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework checks whether each application has accessed data backup and restoration. If yes, the backup and restore framework backs up or restores data based on the application's configuration file. - [Backup and restoration triggered by system applications](app-file-backup.md): Only system applications can trigger data backup and restoration. After data backup or restoration is triggered, the backup and restoration framework locates the applications that have accessed the data backup and restoration framework and backs up or restores data based on the application's configuration file.
# Backing Up and Restoring Application-triggered Data (for System Applications Only) # Backup and Restoration Triggered by System Applications
The backup and restoration module provides a complete data backup and restoration solution for application data, user data, and system services on devices. You can implement data backup or restoration for applications by performing the following operations: The backup and restoration framework provides a complete data backup and restoration solution for application data, user data, and system services on devices. You can follow the procedure below to enable an application to trigger data backup or restoration:
- [Obtaining the capability file](#obtaining-the-capability-file): Obtain the capability file of all applications of the system user. The capability file is indispensable for data backup and restoration. - [Obtain capability files](#obtaining-capability-files): Obtain capability files of all applications of the user in the system. The capability files are indispensable for data backup and restoration.
- [Backing up application data](#backing-up-application-data): Select the application data to be backed up based on the application information provided by the capability file, and back up the data. - [Back up application data](#backing-up-application-data): Back up the application data based on the application information in the capability files.
- [Restoring application data](#restoring-application-data): Select the application data to be restored based on the application information provided in the capability file and restore the data. - [Restore application data](#restoring-application-data): Restore the application data based on the application information in the capability files.
- [Installing the application during data restoration](#installing-the-application-during-data-restoration): Install the application if the application has not been installed. As an extended function of application data restoration, this function allows the application to be installed on the device before data restoration. - [Install the application during data restoration](#installing-the-application-during-data-restoration): Install the application if the application with data to be restored has not been installed. As an extended function of application data restoration, this function allows the application to be installed on the device before data restoration.
## How to Develop ## How to Develop
...@@ -16,7 +16,7 @@ For details about the APIs to be used, see [Backup and Restoration](../reference ...@@ -16,7 +16,7 @@ For details about the APIs to be used, see [Backup and Restoration](../reference
Before using the APIs, you need to: Before using the APIs, you need to:
1. Apply for the ohos.permission.BACKUP permission. For details, see [Apply for permissions](../security/accesstoken-guidelines.md). 1. Apply for the **ohos.permission.BACKUP** permission. For details, see [Apply for Permissions](../security/accesstoken-guidelines.md).
2. Import **@ohos.file.backup**. 2. Import **@ohos.file.backup**.
...@@ -24,13 +24,13 @@ Before using the APIs, you need to: ...@@ -24,13 +24,13 @@ Before using the APIs, you need to:
import backup from '@ohos.file.backup'; import backup from '@ohos.file.backup';
``` ```
## Obtaining the Capability File ## Obtaining Capability Files
Obtain the application capability file of the current system user. This file is indispensable for application data backup and restoration. Obtain capability files of all applications of the current user. The capability files are indispensable for application data backup and restoration.
This file contains the device type and version and basic application information, such as the application name, application data size, application version, whether to allow backup and restoration, and whether to install the application during restoration. The capability file of an application contains the device type, device version, and basic application information, such as the application name, application size, application version, whether to allow backup and restoration, and whether to install the application during restoration.
Use **backup.getLocalCapabilities()** to obtain the capability file. Use **backup.getLocalCapabilities()** to obtain capability files.
```js ```js
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
...@@ -79,9 +79,9 @@ Use **backup.getLocalCapabilities()** to obtain the capability file. ...@@ -79,9 +79,9 @@ Use **backup.getLocalCapabilities()** to obtain the capability file.
## Backing Up Application Data ## Backing Up Application Data
You need to select the application data to be backed up based on the application information provided by the capability file. You can select the application data to be backed up based on the application information in the capability files.
The Backup & Restore service packages the application data into a file. The file handle is returned by the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created. The Backup & Restore service packages the application data to be backed up. The package file handle is returned by the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the **SessionBackup** instance is created.
You can save the file to a local directory as required. You can save the file to a local directory as required.
...@@ -152,9 +152,9 @@ You can save the file to a local directory as required. ...@@ -152,9 +152,9 @@ You can save the file to a local directory as required.
## Restoring Application Data ## Restoring Application Data
You can select the application data to be restored based on the application information provided by the capability file. You can select the application data to be restored based on the application information in the capability files.
During the restoration, the Backup and Restore service returns the file handle of the application data to be restored in the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the instance is created based on the [getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle) called. Then, the data to be restored is written to the file handle based on the [uri](../reference/apis/js-apis-file-backup.md#filemeta) returned. After the data is written, use [publishFile()](../reference/apis/js-apis-file-backup.md#publishfile) to notify the service that the data write is complete. The Backup and Restore service returns the file handle of the application data to be restored in the [onFileReady](../reference/apis/js-apis-file-backup.md#onfileready) callback registered when the **SessionRestore** instance is created. The file handle is obtained by [getFileHandle](../reference/apis/js-apis-file-backup.md#getfilehandle). Then, the data to be restored is written to the file handle based on the [uri](../reference/apis/js-apis-file-backup.md#filemeta) returned. After the data is written, use [publishFile()](../reference/apis/js-apis-file-backup.md#publishfile) to notify the service that the data write is complete.
When all the data of the application is ready, the service starts to restore the application data. When all the data of the application is ready, the service starts to restore the application data.
...@@ -184,7 +184,7 @@ When all the data of the application is ready, the service starts to restore the ...@@ -184,7 +184,7 @@ When all the data of the application is ready, the service starts to restore the
} }
fs.copyFileSync(bundlePath, file.fd); fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd); fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready. // After the data is transferred, notify the server that the files are ready.
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
...@@ -220,11 +220,11 @@ When all the data of the application is ready, the service starts to restore the ...@@ -220,11 +220,11 @@ When all the data of the application is ready, the service starts to restore the
"com.example.hiworld", "com.example.hiworld",
] ]
// You can obtain the capability file based on actual situation. The following is an example only. // You can obtain the capability file based on actual situation. The following is an example only.
// You can also construct a capability file as required. // You can also construct capability files as required.
let fileData = await backup.getLocalCapabilities(); let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps); await g_session.appendBundles(fileData.fd, backupApps);
console.info('appendBundles success'); console.info('appendBundles success');
// After the application to be restored is added, call getFileHandle() to obtain the handle of the application file to be restored based on the application name. // After the applications to be restored are added, call getFileHandle() to obtain the handles of the application files to be restored based on the application name.
// The number of application data files to be restored varies depending on the number of backup files. The following is only an example. // The number of application data files to be restored varies depending on the number of backup files. The following is only an example.
await g_session.getFileHandle({ await g_session.getFileHandle({
bundleName: restoreApps[0], bundleName: restoreApps[0],
...@@ -240,11 +240,11 @@ When all the data of the application is ready, the service starts to restore the ...@@ -240,11 +240,11 @@ When all the data of the application is ready, the service starts to restore the
## Installing the Application During Data Restoration ## Installing the Application During Data Restoration
You can enable the application to be installed before application data restoration. To achieve this purpose, the value of **needToInstall** in **bundleInfos** in the [capability file](#obtaining-the-capability-file) must be **true**. If the application has not been installed, you can install the application and then restore the application data. To achieve this purpose, the value of **needToInstall** in **bundleInfos** in the [capability file](#obtaining-capability-files) must be **true**.
> **NOTE** > **NOTE**
> - [Application data backup](#backing-up-application-data) does not support backup of the application installation package. Therefore, you need to obtain the application installation package. > - [Application data backup](#backing-up-application-data) does not support backup of the application installation package. Therefore, you need to obtain the application installation package.
> - To obtain the file handle of the application installation package, call [getFileHandle()](../reference/apis/js-apis-file-backup.md#getfilehandle) with **FileMeta.uri** set to **/data/storage/el2/restore/bundle.hap**. The file handle of the application installation package is returned through the **onFileReady()** callback registered when the instance is created. The returned **File.uri** is **data/storage/el2/restore/bundle.hap**. > - To obtain the file handle of an application installation package, call [getFileHandle()](../reference/apis/js-apis-file-backup.md#getfilehandle) with **FileMeta.uri** set to **/data/storage/el2/restore/bundle.hap**. The file handle of the application installation package is returned through the **onFileReady()** callback registered when the instance is created. The returned **File.uri** is **data/storage/el2/restore/bundle.hap**.
**Example** **Example**
...@@ -277,7 +277,7 @@ You can enable the application to be installed before application data restorati ...@@ -277,7 +277,7 @@ You can enable the application to be installed before application data restorati
} }
fs.copyFileSync(bundlePath, file.fd); fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd); fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready. // After the data is transferred, notify the server that the files are ready.
publishFile(file); publishFile(file);
console.info('onFileReady success'); console.info('onFileReady success');
}, },
......
...@@ -4,8 +4,8 @@ Application files are files of an application, including the application's insta ...@@ -4,8 +4,8 @@ Application files are files of an application, including the application's insta
- The data used and saved by an application is stored in files, key-value (KV) pairs, and databases in a dedicated directory on a device. This directory is called application file directory, and the files in the directory are application files. - The data used and saved by an application is stored in files, key-value (KV) pairs, and databases in a dedicated directory on a device. This directory is called application file directory, and the files in the directory are application files.
- The directories visible to an application include the application file directory and a directory containing the minimum system files required for the running of the application. These two directories constitute an [application sandbox directory](app-sandbox-directory.md). That means, the application file directory is a subset of the application sandbox directory. - The directories visible to an application include the application file directory and a directory containing the minimum system files required for the running of the application. These two directories constitute an [application sandbox directory](app-sandbox-directory.md). That is, the application file directory is a subset of the application sandbox directory.
- The system files and directories are read-only for the application. The application can only save files to sub-directories in the [application file directory](app-sandbox-directory.md#application-file-directory-and-application-file-path) based on certain rules. - The system files and directories are read-only for the application. The application can only save files to sub-directories in the [application file directory](app-sandbox-directory.md#application-file-directory-and-application-file-path) based on certain rules.
The following topics describe the application sandbox, application file directories, and how to access, manage, and share application files. The following topics describe the application sandbox, application file directories, and how to access, manage, and share application files.
\ No newline at end of file
# Uploading and Downloading an Application File # Uploading and Downloading an Application File
This topic describes how to upload an application file to a network server and download a network resource file from a network server to a local application directory. This topic describes how to enable an application to upload an application file to a network server and download a network resource file from a network server to a local application directory.
## Uploading an Application File ## Uploading an Application File
...@@ -10,7 +10,7 @@ You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()* ...@@ -10,7 +10,7 @@ You can use [ohos.request](../reference/apis/js-apis-request.md) **uploadFile()*
> >
> Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded. > Currently, only the files in the **cache/** directories (**cacheDir**) can be uploaded.
> >
> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md). > The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to upload a file in the **cache** directory of an application to a network server. The following example demonstrates how to upload a file in the **cache** directory of an application to a network server.
...@@ -62,13 +62,13 @@ try { ...@@ -62,13 +62,13 @@ try {
## Downloading a Network Resource File to the Application File Directory ## Downloading a Network Resource File to the Application File Directory
You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the ([ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files. For details, see [Accessing Application Files](app-file-access.md). The system service proxy implements the download. You can use [ohos.request](../reference/apis/js-apis-request.md) **downloadFile()** to download network resource files to a local application directory. You can use the [ohos.file.fs](../reference/apis/js-apis-file-fs.md) APIs to access the downloaded files in the same way as [accessing application files](app-file-access.md). The system service proxy implements the download.
> **NOTE** > **NOTE**
> >
> Currently, network resource files can be downloaded only to an application file directory. > Currently, network resource files can be downloaded only to an application file directory.
> >
> <br>The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md). > The **ohos.permission.INTERNET** permission is required for using **ohos.request**. For details about how to apply for a permission, see [Applying for Permissions](../security/accesstoken-guidelines.md).
The following example demonstrates how to download a network resource file to a local application file directory. The following example demonstrates how to download a network resource file to a local application file directory.
......
...@@ -10,22 +10,22 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ...@@ -10,22 +10,22 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
| Module| API| Description| | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| | \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.|
| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| | \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.|
| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| | \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.|
**Table 2** Attributes for application space statistics **Table 2** Attributes for application space statistics
| BundleStats Attribute| Description| Directory for Statistics| | BundleStats Attribute| Description| Directory for Statistics|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| appSize | Size of the application installation files, in bytes.| Application installation file directory:<br>**/data/storage/el1/bundle **| | appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle |
| cacheSize | Size of the application cache files, in bytes.| Application cache file directories:<br>**/data/storage/el1/base/cache**<br>**/data/storage/el1/base/haps/entry/cache**<br>**/data/storage/el2/base/cache**<br>**/data/storage/el2/base/haps/entry/cache **| | cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache<br>/data/storage/el1/base/haps/entry/cache<br>/data/storage/el2/base/cache<br>/data/storage/el2/base/haps/entry/cache |
| dataSize | Size of the application files (excluding the application installation files and cache files), in bytes.| The application files include local files, distributed files, and database files.<br>- Local application file directories (parent directories of the **cache** directories):<br>**/data/storage/el1/base**<br>**/data/storage/el2/base**<br>- Distributed application directory:<br>/data/storage/el2/distributedfiles<br>- Database directories:<br>**/data/storage/el1/database**<br>**/data/storage/el2/database **| | dataSize | Size of the application files (excluding the application installation files and cache files), in bytes.| The application files include local files, distributed files, and database files.<br>- Local application file directories (parent directories of the **cache** directories):<br>**/data/storage/el1/base**<br>**/data/storage/el2/base**<br>- Distributed application directory: **/data/storage/el2/distributedfiles**<br>- Database directories:<br>**/data/storage/el1/database**<br>**/data/storage/el2/database** |
## Development Example ## Development Example
- Obtain the free space of **/data** of the file system. - Obtain the free space of **/data** of the file system.
```ts ```ts
import statvfs from '@ohos.file.statvfs'; import statvfs from '@ohos.file.statvfs';
...@@ -40,7 +40,7 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi ...@@ -40,7 +40,7 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis/js-apis-fi
``` ```
- Obtain the space occupied by the current application. - Obtain the space occupied by the current application.
```ts ```ts
import storageStatistics from "@ohos.file.storageStatistics"; import storageStatistics from "@ohos.file.storageStatistics";
......
# Application Sandbox Directory # Application Sandbox Directory
The application sandbox is an isolation mechanism to prevent data from being accessed through path traversal. This mechanism allows only the application sandbox directory visible to an application. The application sandbox is an isolation mechanism used to prevent malicious data access through path traversal. With this mechanism, only the application sandbox directory is visible to an application.
- The system maps a dedicated application sandbox directory in the internal storage space for each application. The directory is a collection of the [application file directory](app-file-overview.md) and a directory containing the minimum system files required during application's runtime. - The system has a dedicated application sandbox directory in the internal storage to map the directory of each application. The application sandbox directory holds [application files](app-file-overview.md) and the minimum system files required for running of the application.
- The application sandbox specifies the minimum range of data visible to each application. In the application sandbox directory, an application can access only its own application files and the system files required for its running. The application cannot access files of other applications. The security of application files is protected in this way. - The application sandbox specifies the minimum data range visible to each application. In the application sandbox directory, an application can access only its own application files and the system files required for its running. The application cannot access files of other applications. This ensures application file security.
- In each application sandbox directory, the application can save and process its own application files in the [application file directory](app-file-overview.md), and can only read the system files and directories. The application can access [user files](user-file-overview.md) by using specific APIs only with authorization from the user. - In each application sandbox directory, the application can save and process its application files in the [application file directory](app-file-overview.md), and can only read the system files and directories. To access [user files](user-file-overview.md), the application need to call specific APIs and have authorization from the user.
The following figure illustrates the file access scope and modes for an application in an application sandbox. The following figure illustrates the file access mechanism in an application sandbox.
**Figure 1** File access mechanism in an application sandbox
**Figure 1** File access in an application sandbox
![Application sandbox file access relationship](figures/application-sandbox-file-access-relationship.png) ![Application sandbox file access relationship](figures/application-sandbox-file-access-relationship.png)
## Application Sandbox Directory and Application Sandbox Path ## Application Sandbox Directory and Application Sandbox Path
With the application sandbox mechanism, an application cannot learn the location and existence of other applications' directories and user file directories. In addition, all the application directories visible to an application are isolated by permission and namespace to form an independent directory view and shield the real (physical) paths. With the application sandbox mechanism, an application is not aware of the existence and location of other applications' directories and user file directories. Even the application directories visible to an application are isolated by permission and namespace to form an independent directory view and shield the real (physical) paths.
- As shown in the following figure, the sandbox mechanism minimizes the number of directories and files visible to a common application (third-party application). The directories and file paths visible to a common application are different from those visible to a system process. The path of a file or folder in the application sandbox directory visible to a common application is called the application sandbox path. - As shown in the following figure, the sandbox mechanism minimizes the number of directories and files visible to a common application (third-party application). In addition, the directories and file paths visible to a common application are different from those visible to a system process. The path of a file or folder in the application sandbox directory visible to a common application is called the application sandbox path.
- You can view the real application paths (the directory view visible to a system process) in the HDC shell environment. For details about the mappings between the application sandbox paths and real application paths, see [Mappings Between Application Sandbox Paths and Physical Paths](send-file-to-app-sandbox.md#mappings-between-application-sandbox-paths-and-physical-paths). - You can view the real application paths (the directory view visible to a system process) in the HDC shell environment. For details about the mappings between the application sandbox paths and real application paths, see [Mappings Between Application Sandbox Paths and Physical Paths](send-file-to-app-sandbox.md#mappings-between-application-sandbox-paths-and-physical-paths).
- The application sandbox paths and physical paths are not in one-to-one mappings. The application sandbox paths are always less than the physical paths. You may not obtain the application sandbox path based on a physical path in certain cases, but you can obtain the physical path based on an application sandbox path. - The application sandbox paths and physical paths are not in one-to-one mappings. The application sandbox paths are always less than the physical paths. You may not obtain the application sandbox path based on a physical path in certain cases, but you can obtain the physical path based on an application sandbox path.
**Figure 2** Different directory views to processes and applications **Figure 2** Different directory views to processes and applications
![Application sandbox path](figures/application-sandbox-path.png) ![Application sandbox path](figures/application-sandbox-path.png)
## Application File Directory and Application File Path ## Application File Directory and Application File Path
...@@ -32,31 +34,33 @@ The application sandbox directory includes application file directories and syst ...@@ -32,31 +34,33 @@ The application sandbox directory includes application file directories and syst
The system file directories visible to an application are preset by OpenHarmony. The system file directories visible to an application are preset by OpenHarmony.
The following figure shows the application file directories. The path of a file or a folder in the application file directory is called the application file path. The file paths in the application file directory have different attributes and characteristics. The following figure shows the application file directories. The path of a file or a folder in the application file directory is called the application file path. The sub-directories in the application file directory have different attributes.
**Figure 3** Application file directory structure
**Figure 3** Application file directory structure
![Application file directory structure](figures/application-file-directory-structure.png) ![Application file directory structure](figures/application-file-directory-structure.png)
1. Level 1 directory **data/**: indicates the application file directory. 1. Level 1 directory **data/** indicates the application file directory.
2. Level 2 directory **storage/**: indicates a directory for persistent files of the application. 2. Level 2 directory **storage/** indicates a directory for persistent files of the application.
3. Level 3 directories **el1/** and **el2/**: indicate directories for files of different encryption levels (els). 3. Level 3 directories **el1/** and **el2/** indicate directories for files of different encryption levels (els).
- **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files. - **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files.
- **el2**: directory for the data that can be accessed only after at lease one successful unlocking operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.<br> - **el2**: directory for the data that can be accessed only after at lease one successful unlock operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.
Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels).
Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about the operations on **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels).
4. Level 4 and level 5 directories: 4. Level 4 and level 5 directories:
The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders. The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders.
You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md). You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state has one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md).
For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md). For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md).
> **NOTE** > **NOTE**
> >
> - Do not directly use file paths made up by level 1 to level 4 directory names. Incompatibility problems may occur if the directory names are changed in later versions. > - Do not use file paths made up by level 1 to level 4 directory names. Incompatibility problems may occur if the directory names are changed in later versions.
> - Use **Context** to obtain application file paths, which include but are not limited to the directories highlighted in green in **Figure 3**. > - Use **Context** to obtain the application file paths, including but are not limited to the directories highlighted in green in **Figure 3**.
The following table describes the application file paths and lifecycle. The following table describes the application file paths and lifecycle.
...@@ -64,7 +68,7 @@ The following figure shows the application file directories. The path of a file ...@@ -64,7 +68,7 @@ The following figure shows the application file directories. The path of a file
| Folder| Context Attribute Name| Type| Description| | Folder| Context Attribute Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs of the application after an application is installed.<br>This directory is cleared when the application is uninstalled.<br> Do not access resource files by concatenating paths. Use [@ohos.resourceManager](../reference/apis/js-apis-resource-manager.md) instead. | | bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs after an application is installed.<br>This directory is cleared when the application is uninstalled.<br> Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../reference/apis/js-apis-resource-manager.md) instead.|
| base | NA | Directory for local device files| Directory for saving the application's persistent data on the device. Subdirectories include **files/**, **cache/**, **temp/**, and **haps/**.<br>This directory is cleared when the application is uninstalled.| | base | NA | Directory for local device files| Directory for saving the application's persistent data on the device. Subdirectories include **files/**, **cache/**, **temp/**, and **haps/**.<br>This directory is cleared when the application is uninstalled.|
| database | databaseDir | Database directory| Directory in **el1** for saving the files operated by the distributed database service.<br>This directory is cleared when the application is uninstalled.| | database | databaseDir | Database directory| Directory in **el1** for saving the files operated by the distributed database service.<br>This directory is cleared when the application is uninstalled.|
| distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.| | distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.<br>This directory is cleared when the application is uninstalled.|
...@@ -73,7 +77,7 @@ The following figure shows the application file directories. The path of a file ...@@ -73,7 +77,7 @@ The following figure shows the application file directories. The path of a file
| preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).| | preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preference data managed by using database APIs.<br>This directory is cleared when the application is uninstalled. For details, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).|
| temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.| | temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device. <br>This directory is cleared when the application exits.|
The application file paths are used in the following scenarios: The application scenarios of the application file directories are as follows:
- Installation file directory<br> - Installation file directory<br>
Used to store the code resource data of the application, including the HAPs of the application, reusable library files, and plug-ins. The code stored in this directory can be dynamically loaded. Used to store the code resource data of the application, including the HAPs of the application, reusable library files, and plug-ins. The code stored in this directory can be dynamically loaded.
...@@ -83,9 +87,9 @@ The following figure shows the application file directories. The path of a file ...@@ -83,9 +87,9 @@ The following figure shows the application file directories. The path of a file
Used to store the application's data used for distributed scenarios, including file sharing, file backup, and file processing across devices. The data stored in this directory enables the application to run smoothly on multiple devices. Used to store the application's data used for distributed scenarios, including file sharing, file backup, and file processing across devices. The data stored in this directory enables the application to run smoothly on multiple devices.
- Application file directory<br> - Application file directory<br>
Used to store private data of the application, including persistent files, images, media files, and log files. The data is stored in this directory to ensure privacy, security, and permanent validity. Used to store private data of the application, including persistent files, images, media files, and log files. The data is stored in this directory to ensure privacy, security, and permanent validity.
- Cached application file directory<br> - Cache application file directory<br>
Used to store cached data of the application, including offline data, cached images, database backup, and temporary files. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory. Used to store cached data of the application, including offline data, cached images, database backup, and temporary files. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory.
- Preferences file directory<br> - Preferences file directory<br>
Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data. Used to store application preferences data, including preference files and configuration files. This directory applied to storing only a small amount of data.
- Temporary file directory<br> - Temporary file directory<br>
Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package files. The data stored in this directory is deleted after being used. Used to store temporarily generated data of an application, including cached database data and images, temporary log files, downloaded application installation package. The data stored in this directory is deleted after being used.
\ No newline at end of file
# Developing a FileManager Application (for System Applications Only) # Developing a File Manager Application (for System Applications Only)
OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own **FileManager** as required. OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own file manager application as required.
## Available APIs ## Available APIs
For details about the APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md). For details about the APIs used to develop a file manager application, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
## How to Develop ## How to Develop
1. Configure the permissions required and import dependent modules. 1. Apply for permissions required.<br>
Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). Apply for the **ohos.permission.FILE_ACCESS_MANAGER** and **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
> **NOTE** > **NOTE**
> >
> **ohos.permission.FILE_ACCESS_MANAGER** is required for using the user file access framework APIs. > **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
> >
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** is required for querying information about file management server applications supported by the system. > **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
2. Import the dependent modules. 2. Import dependent modules.
```ts ```ts
import fileAccess from '@ohos.file.fileAccess'; import fileAccess from '@ohos.file.fileAccess';
...@@ -26,8 +26,8 @@ For details about the APIs, see [User File Access and Management](../reference/a ...@@ -26,8 +26,8 @@ For details about the APIs, see [User File Access and Management](../reference/a
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development. The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information. 3. Query device information.<br>
You can obtain attributes of one or all devices managed by the file management server in the current system. You can also filter devices as required. You can obtain attributes of the devices managed by one or all file management servers in the system. You can also filter devices as required.
In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices. In the user file access framework, **RootInfo** indicates the attribute information of a device. For example, obtain **RootInfo** of all devices.
...@@ -68,19 +68,19 @@ For details about the APIs, see [User File Access and Management](../reference/a ...@@ -68,19 +68,19 @@ For details about the APIs, see [User File Access and Management](../reference/a
``` ```
4. View directories. 4. View directories.
In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to traverse all files (directories) of the next level to obtain a **FileIterator** object or use **scanfile()** to filter the specified directories and obtain the **FileIterator** object that meets the conditions. In the user file access framework, **FileInfo** indicates basic information about a file (directory). You can use **listfile()** to obtain a **FileIterator** object that traverses all files (directories) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions.
Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse lower-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse lower-level files or filter specified directories. Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories.
```ts ```ts
// Start from the root directory. // Start from the root directory.
let rootInfo = rootinfos[0]; let rootInfo = rootinfos[0];
let fileInfos = []; let fileInfos = [];
let isDone = false; let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try { try {
let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object. let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the file information of device rootinfos[0] that meets the specified conditions and return an iteration object. // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if (!fileIterator) { if (!fileIterator) {
console.error("listFile interface returns an undefined object"); console.error("listFile interface returns an undefined object");
return; return;
...@@ -97,12 +97,12 @@ For details about the APIs, see [User File Access and Management](../reference/a ...@@ -97,12 +97,12 @@ For details about the APIs, see [User File Access and Management](../reference/a
} }
// Start from the specified directory. // Start from the specified directory.
let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory. let fileInfoDir = fileInfos[0]; // fileInfoDir indicates information about a directory.
let subFileInfos = []; let subFileInfos = [];
let isDone = false; let isDone = false;
let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria. let filter = {suffix: [".txt", ".jpg", ".xlsx"]}; // Set filter criteria.
try { try {
let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object. let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object. // let fileIterator = rootInfo.scanFile(filter); // Filter the files in the specified directory and return an iterator object.
if (!fileIterator) { if (!fileIterator) {
console.error("listFile interface returns an undefined object"); console.error("listFile interface returns an undefined object");
......
# Distributed File System Overview # Distributed File System Overview
OpenHarmony distributed file system (hmdfs) provides cross-device file access capabilities applicable to the following scenarios: OpenHarmony distributed file system (hmdfs) provides cross-device file access capabilities in the following scenarios:
- The user can use the editing software on one device to edit the files on another device. - The user uses the editing software on one device to edit the files on another device.
- Music stored on a tablet can be directly viewed and played by a in-car system. - Music stored on a tablet can be directly viewed and played by an in-car system.
- The user can use a tablet to view the photos taken by another device. - The user uses a tablet to view the photos taken by another device.
The hmdfs provides a globally consistent access view for each device dynamically connected to a network via DSoftBus and allows you to implement high-performance read and write operations on files with low latency by using basic file system APIs. The hmdfs provides a globally consistent access view for each device dynamically connected to a network via DSoftBus and allows you to implement high-performance read and write operations on files with low latency by using basic file system APIs.
...@@ -16,13 +16,13 @@ The hmdfs provides a globally consistent access view for each device dynamically ...@@ -16,13 +16,13 @@ The hmdfs provides a globally consistent access view for each device dynamically
- distributedfile_daemon: listens for device online status, establishes links over DSoftBus, and applies data transfer policies based on the security level of the device. - distributedfile_daemon: listens for device online status, establishes links over DSoftBus, and applies data transfer policies based on the security level of the device.
- hmdfs: implements a network file system in the kernel, providing cache management, file access, metadata management, and conflict management. - hmdfs: implements a network file system in the kernel and provides cache management, file access, metadata management, and conflict management.
- Buffer management - Cache management
- After devices are connected to form a Virtual Device, hmdfs provides file access capabilities, but does not proactively transmit or copy files. Active copy is required when an application needs to save data to a local directory. - After devices are connected to form a Virtual Device, the hmdfs provides file access capabilities, but does not proactively transmit or copy files. Active copy is required when an application needs to save data to a local directory.
- The hmdfs ensures close-to-open cache consistency, which allows data to flushed when a client closes a file. Then, the latest data can be read when the file is opened on any other client. The hmdfs does not ensure real-time consistency of the file content. - The hmdfs ensures close-to-open cache consistency, which allows data to flushed when a client closes a file. Then, the latest data can be read when the file is opened on any other client. The hmdfs does not ensure real-time consistency of the file content.
- If data written at the peer end has not been flushed to the local end in a timely manner due to network problems, the file system flushes the data to the local end upon the next network access. However, if the data has been modified on the remote end, only the latest data can be flushed. - If data written at the remote end has not been flushed to the local end in a timely manner due to network problems, the file system flushes the data to the local end upon the next network access. However, if the data has been modified on the remote end, only the latest data can be flushed.
- File access - File access
- OpenHarmony provides the same interface, [ohos.file.fs](../reference/apis/js-apis-file-fs.md), for accessing files in the local and distributed file systems. - OpenHarmony provides the unified [ohos.file.fs](../reference/apis/js-apis-file-fs.md) for accessing files in the local and distributed file systems.
- The files in the local file system are accessed in overlay mode. - The files in the local file system are accessed in overlay mode.
- The files on another device are accessed over a synchronous network. - The files on another device are accessed over a synchronous network.
> **NOTE** > **NOTE**
...@@ -31,9 +31,9 @@ The hmdfs provides a globally consistent access view for each device dynamically ...@@ -31,9 +31,9 @@ The hmdfs provides a globally consistent access view for each device dynamically
- Metadata management - Metadata management
- In distributed networking, when a file is created, deleted, or modified on a client, the latest file can be viewed on another client. The speed varies depending on the network status. - In distributed networking, when a file is created, deleted, or modified on a client, the latest file can be viewed on another client. The speed varies depending on the network status.
- If a device goes offline, its data is no longer visible to other devices. However, due to the delay in sensing the device offline, the files of some offline devices may also be visible to other devices. Therefore, you need to consider the network delay in application development. - If a device goes offline, its data is no longer visible to other devices. However, due to the delay in sensing the device offline, the files of some offline devices may also be visible to other devices. Therefore, you need to consider the network delay in application development.
- Conflict Handling - Conflict management
- If a file on the local end and a file on the remote end have the same name, the file on the remote end will be renamed. - If a file name conflict occurs on the local and remote devices, the file on the remote device is renamed.
- If multiple remote devices have files of the same name, the name of the file with the smallest device access ID is retained and the files on other devices will be renamed. - If a file name conflict occurs between multiple remote devices, the name of the file with the smallest device access ID is retained and the files on other devices are renamed.
- In the networking scenario, the directory tree has remote files. If "duplicate file name" is displayed when a file is created, - If the directory tree already has remote files in networking scenario, a file with duplicate file name cannot be created successfully.
- the conflict file is renamed "_conflict_dev_ID". The ID automatically increases from 1. - The conflict files are renamed in "_conflict_dev_ID" format. The IDs automatically increment from 1.
- If a local directory has the same name as a remote directory, "_remote_directory" will be added to the end of the peer directory. - If a local directory and a remote directory have the same name, it does not yield a conflict. If the two directories have files with the same name, "_remote_directory" is added to the end of the remote directory.
# Accessing Files Across Devices # Access Files Across Devices
The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices, you can implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**) across devices by using [ohos.file.fs](app-file-access.md). For example, device A and device B are installed with the same application. After device A and device B are connected to form a Virtual Device, the application on device A can access the files of the same application on Device B. What you need to do is place the files to the distributed directory. The distributed file system provides cross-device file access capabilities for applications. For the same application installed on multiple devices that form a Super Device, you can use [ohos.file.fs](app-file-access.md) APIs to implement read and write of the files in the application's distributed directory (**/data/storage/el2/distributedfiles/**).
## How to Develop For example, device A and device B are installed with the same application. After device A and device B are connected to form a Super Device, the application on device A can access the files in the distributed directory of the same application on Device B.
1. Complete distributed networking for the devices. ## How to Develop
Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
1. Connect the devices to form a Super Device.
Connect the devices to a LAN, and complete authentication of the devices. The devices must have the same account number.
2. Implement cross-device access to the files of the same application. 2. Implement cross-device access to the files of the same application.
Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices. Place the files in the **distributedfiles/** directory of the application sandbox to implement access from difference devices.
For example, create a test file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). For example, create a file in the **distributedfiles/** directory on device A and write data to the file. For details about how to obtain the application context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
import fs from '@ohos.file.fs'; import fs from '@ohos.file.fs';
......
...@@ -2,23 +2,23 @@ ...@@ -2,23 +2,23 @@
The data in an operating system (OS) can be classified into the following types based on the data structure: The data in an operating system (OS) can be classified into the following types based on the data structure:
- Structured data: data that can be defined in a unified data model. The structured data is generally stored in a database. In application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md). - Structured data: data that can be defined in a unified data model and is generally stored in a database. In OpenHarmony application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md).
- Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document. - Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In OpenHarmony application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document.
In the file management module, the files can be classified into the following types based on the file owner: In the file management module, the files can be classified into the following types based on the file owner:
- [Application files](app-file-overview.md): files of an application, including the application's installation files, resource files, and cached files. - [Application files](app-file-overview.md): files of an application, including the installation files, resource files, and cache files of the application.
- [User files](user-file-overview.md): files of a user who logs in to the device, including the user's images, video and audio clips, and documents. - [User files](user-file-overview.md): files of a user who has logged in to the device. User files include the user's images, video and audio clips, and documents.
- System files: files irrelevant to applications and users, including public libraries, device files, and system resource files. System files do not need to be managed by developers and are not described in this document. - System files: files irrelevant to applications and users. System files include public libraries, device files, and system resource files. The system files do not need to be managed by developers and are not described in this document.
The file systems can be classified into the following types based on the file storage location (data source location): The file systems can be classified into the following types based on the file storage location (data source location):
- Local file system: provides capabilities for accessing the files stored on a local device or its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document. - Local file system: allows access to the files stored on a device and its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document.
- [Distributed file system](distributed-fs-overview.md): provides capabilities for accessing files across devices, which are connected through a computer network. - [Distributed file system](distributed-fs-overview.md): allows access to files across devices, which include not only the local device and its external storage devices, but also the devices connected over a computer network.
**Figure 1** Files in an OS **Figure 1** Files in an OS
......
# Managing External Storage Devices (for System Applications Only) # Managing External Storage Devices (for System Applications Only)
External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device. Because external storage devices are pluggable, OpenHarmony provides functions for listening for the device insertion/removal events and mounting/unmounting an external storage device.
External storage devices are managed by the StorageManager and StorageDaemon services. StorageDaemon implements the underlying listening and mount/unmount functions. StorageManager provides status change notifications, query, and management capabilities for system applications. External storage devices are managed by the StorageManager and StorageDaemon services. StorageDaemon implements underlying listening and mount/unmount functions. StorageManager provides status change notifications and query and management of external storage devices for system applications.
**Figure 1** External storage device management **Figure 1** External storage device management
...@@ -10,12 +10,12 @@ External storage devices are managed by the StorageManager and StorageDaemon ser ...@@ -10,12 +10,12 @@ External storage devices are managed by the StorageManager and StorageDaemon ser
- When an external storage device is inserted, the StorageDaemon process obtains an insertion event over netlink and creates a disk device and volume. The created volume is in the **UNMOUNTED** state. - When an external storage device is inserted, the StorageDaemon process obtains an insertion event over netlink and creates a disk device and volume. The created volume is in the **UNMOUNTED** state.
- Then, the StorageDaemon process checks the volume. During the check process, the volume is in the **CHECKING** state. - Then, the StorageDaemon process checks the volume. The volume transits to the **CHECKING** state.
- The StorageDaemon process mounts the volume if the check is successful. If the mount operation is successful, the volume state changes to **MOUNTED** and StorageManager is instructed to send the COMMON_EVENT_VOLUME_MOUNTED broadcast. - The StorageDaemon process mounts the volume if the check is successful. If the mount operation is successful, the volume state changes to **MOUNTED** and StorageManager is instructed to send the COMMON_EVENT_VOLUME_MOUNTED broadcast.
- If the check fails, the volume state changes to **UNMOUNTED**. - If the check fails, the volume state changes to **UNMOUNTED**.
- For a volume in the **MOUNTED** state: - For a volume in the **MOUNTED** state:
- If the device is directly removed, the volume information will be deleted and COMMON_EVENT_VOLUME_BAD_REMOVAL is broadcast. - If the device is directly removed, the volume information is deleted and COMMON_EVENT_VOLUME_BAD_REMOVAL is broadcast.
- If the user chooses **Eject device**, the volume state changes to **EJECTING** and the COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast. - If the user chooses **Eject device**, the volume state changes to **EJECTING** and the COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast.
- For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED. - For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED.
...@@ -38,13 +38,13 @@ The following table describes the broadcast related parameters. ...@@ -38,13 +38,13 @@ The following table describes the broadcast related parameters.
## How to Develop ## How to Develop
Subscribe to broadcast events to notify the insertion and removal of external storage devices. The volumes can be queried and managed based on the volume information obtained from the broadcast. You can subscribe to broadcast events to observe the insertion and removal of external storage devices, and query or manage volumes based on the volume information obtained from the broadcast.
1. Apply for permissions. 1. Apply for permissions.<br>
Apply for the **ohos.permission.STORAGE_MANAGER** permission for subscribing to volume broadcast events. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). Apply for the **ohos.permission.STORAGE_MANAGER** permission for subscribing to volume broadcast events. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Subscribe to broadcast events. 2. Subscribe to broadcast events.<br>
Subscribe to the following events: You can subscribe to the following events:
- "usual.event.data.VOLUME_REMOVED": The device is removed. - "usual.event.data.VOLUME_REMOVED": The device is removed.
- "usual.event.data.VOLUME_UNMOUNTED": The volume is unmounted. - "usual.event.data.VOLUME_UNMOUNTED": The volume is unmounted.
...@@ -68,7 +68,7 @@ Subscribe to broadcast events to notify the insertion and removal of external st ...@@ -68,7 +68,7 @@ Subscribe to broadcast events to notify the insertion and removal of external st
let subscriber = await CommonEvent.createSubscriber(subscribeInfo); let subscriber = await CommonEvent.createSubscriber(subscribeInfo);
``` ```
3. Obtain the volume information from the broadcast. 3. Obtain volume information from the broadcast.
```ts ```ts
CommonEvent.subscribe(subscriber, function (err, data) { CommonEvent.subscribe(subscriber, function (err, data) {
......
# Media Asset (Image, Video, and Album) Change Notification Management # Managing Media Asset Change Notifications
The **photoAccessHelper** module provides APIs for listening for media asset changes. The **photoAccessHelper** module provides APIs for listening for media asset (image, video, and album) changes.
> **NOTE** > **NOTE**
> >
> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. > Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).<br>
> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. > By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
The APIs related to media asset change notifications can be called asynchronously only in callback mode. This topic describes how to use some APIs. For more information about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). The APIs related to media asset change notifications can be called asynchronously only in callback mode. This topic describes how to use some APIs. For more information about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
...@@ -16,14 +16,14 @@ Use [registerChange](../reference/apis/js-apis-photoAccessHelper.md#registerchan ...@@ -16,14 +16,14 @@ Use [registerChange](../reference/apis/js-apis-photoAccessHelper.md#registerchan
### Registering a Listener for a File Asset ### Registering a Listener for a File Asset
Registers a listener for the specified file asset. When the observed file asset changes, the listener callback will be invoked to return the change. Register a listener for the specified file asset. When the observed file asset changes, the listener callback will be invoked to return the change.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Register a listener for an image. When the image is favorited, the listener callback will be invoked. Example: Listener for changes of an image. When the image is favorited, the listener callback will be invoked.
**How to Develop** **How to Develop**
...@@ -60,18 +60,18 @@ try { ...@@ -60,18 +60,18 @@ try {
### Registering a Listener for an Album ### Registering a Listener for an Album
Registers a listener for an album. When the observed album changes, the listener callback will be invoked to return the change. Register a listener for an album. When the observed album changes, the listener callback will be invoked to return the change.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Register a listener for a user album. When the album is renamed, the listener callback will be invoked. Example: Listener for a user album. When the album is renamed, the listener callback will be invoked.
**How to Develop** **How to Develop**
1. [Obtain the user album](photoAccessHelper-userAlbum-guidelines.md#obtaining-a-use-album]. 1. [Obtain a user album](photoAccessHelper-userAlbum-guidelines.md#obtaining-a-user-album).
2. Register a listener for the user album. 2. Register a listener for the user album.
3. Rename the user album. 3. Rename the user album.
...@@ -106,24 +106,30 @@ try { ...@@ -106,24 +106,30 @@ try {
## Fuzzy Listening ## Fuzzy Listening
You can set **forChildUris** to **true** to register fuzzy listening. When **uri** is an album URI, the value **true** of **forChildUris** listens for the changes of the files in the album, and the value **false** listens for only the changes of the album itself. <br>If **uri** is the URI of a **fileAsset**, there is no difference between **true** and **false** for **forChildUris**.<br>If **uri** is **DefaultChangeUri**, **forChildUris** must be set to **true**. If **forChildUris** is **false**, the URI cannot be found and no message can be received. You can set **forChildUris** to **true** to enable fuzzy listening.
### Registering a Listener for All FileAssets If **uri** is an album URI, the value **true** of **forChildUris** enables listening for the changes of the files in the album, and the value **false** enables listening for only the changes of the album itself.
Register listening for all FileAssets. When an observed FileAsset changes, the listener callback will be invoked. If **uri** is the URI of a file asset, there is no difference between **true** and **false** for **forChildUris**.
If **uri** is **DefaultChangeUri**, **forChildUris** must be set to **true**. If **forChildUris** is **false**, the URI cannot be found and no notification can be received.
### Registering a Listener for All File Assets
Register listening for all file assets. When an observed file asset changes, the listener callback will be invoked.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Register a listener for all FileAssets. When an observed FileAsset is favorited, the listener callback will be invoked. Example: Register a listener for all file assets. When an observed file asset is favorited, the listener callback will be invoked.
**How to Develop** **How to Develop**
1. Register a listener for all FileAssets. 1. Register a listener for all file assets.
2. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). 2. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
3. Add the media asset obtained to **Favorites**. 3. Add the obtained media asset to **Favorites**.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
...@@ -150,22 +156,22 @@ try { ...@@ -150,22 +156,22 @@ try {
} }
``` ```
## Unregistering the Listening for a URI ## Unregistering Listening for a URI
Use [unRegisterChange](../reference/apis/js-apis-photoAccessHelper.md#unregisterchange) to unregister the listening for the specified URI. Multiple listeners can be registered for a URI. If multiple listener callbacks exist, you can unregister a listener callback registered. If callback is not specified, all listeners of the URI will be unregistered. Use [unRegisterChange](../reference/apis/js-apis-photoAccessHelper.md#unregisterchange) to unregister the listening for the specified URI. Multiple listeners can be registered for a URI. If multiple listener callbacks exist, you can unregister a listener callback registered. If callback is not specified, all listeners of the URI will be unregistered.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Unregister the listening for an image. After that, the corresponding listener callback is not triggered when the image favorites status is changed. Example: Unregister listening for an image. After that, the unregistered listener callback will not be invoked when the image favorite status is changed.
**How to Develop** **How to Develop**
1. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). 1. [Obtain a media asset](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
2. Unregister the listening for the URI of the media asset obtained. 2. Unregister listening for the URI of the media asset obtained.
3. Add the media asset obtained to **Favorites**. 3. Add the obtained media asset to **Favorites**.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
......
# PhotoAccessHelper Overview # PhotoAccessHelper Overview
**PhotoAccessHelper** provides album management capabilities, including creating and accessing an album and accessing and modifying media data in albums. You can use the APIs provided by **PhotoAccessHelper** to manage: **PhotoAccessHelper** provides album management capabilities, including creating and accessing an album and accessing and modifying media data in albums. You can use the APIs provided by **PhotoAccessHelper** to:
- [Media assets (images and videos)](photoAccessHelper-resource-guidelines.md), including: - [Manage media assets (images and videos)](photoAccessHelper-resource-guidelines.md), including:
- Obtaining the specified media assets. - Obtaining the specified media assets.
- Obtaining an image or video thumbnail. - Obtaining image and video thumbnails.
- Creating a media asset. - Creating a media asset.
- Renaming a media asset. - Renaming a media asset.
- Moving a media asset to the trash. - Moving a media asset to the trash.
- [User Albums](photoAccessHelper-userAlbum-guidelines.md), including: - [Manage user albums](photoAccessHelper-userAlbum-guidelines.md), including:
- Creating a user album. - Creating a user album.
- Obtaining a user album. - Obtaining a user album.
- Renaming a user album. - Renaming a user album.
...@@ -16,39 +16,38 @@ ...@@ -16,39 +16,38 @@
- Obtaining images and videos from a user album. - Obtaining images and videos from a user album.
- Removing images and videos from a user album. - Removing images and videos from a user album.
- Deleting a user album. - Deleting a user album.
- [System albums](photoAccessHelper-systemAlbum-guidelines.md), including: - [Manage system albums](photoAccessHelper-systemAlbum-guidelines.md), including:
- Favorites - Favorites
- Video album - Videos
- Screenshot album - Screenshots
- [Media asset (image, video, and album) change notifications](photoAccessHelper-notify-guidelines.md), including: - [Manage media asset (image, video, and album) change notifications](photoAccessHelper-notify-guidelines.md), including:
- Registering listening for a specified URI. - Registering listening for the specified URI.
- Unregistering the listening for a specified URI. - Unregistering the listening for the specified URI.
> **NOTE** > **NOTE**
> > This development guide applies only to API version 10 based on the stage model.
> The **PhotoAccessHelper** development guides apply only to API version 10 based on the stage model.
An application needs to obtain a **photoAccessHelper** instance before accessing and modifying the media data in an album. User personal data is involved in the **photoAccessHelper** module. Therefore, the application needs to apply for the related read and write permissions. Unless otherwise specified, the APIs of the **photoAccessHelper** module apply to **pages/index.ets** of the project or other customized .ets files by default. An application needs to obtain a **PhotoAccessHelper** instance before accessing and modifying the media data in an album. User personal data is involved in the **photoAccessHelper** module. Therefore, the application needs to apply for the related read and write permissions. Unless otherwise specified, the APIs of the **photoAccessHelper** module are used in **pages/index.ets** of the project or other customized .ets files by default.
Before using the **PhotoAccessHelper** APIs, you need to: Before using the **PhotoAccessHelper** APIs, you need to:
- [Obtain a **photoAccessHelper** instance.](#obtaining-a-photoaccesshelper-instance) - [Obtain a **PhotoAccessHelper** instance](#obtaining-a-photoaccesshelper-instance).
- [Apply for permissions.](#applying-for-permissions) - [Apply for permissions](#applying-for-permissions).
## Obtaining a photoAccessHelper Instance ## Obtaining a PhotoAccessHelper Instance
The application needs to call [getPhotoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) to obtain a **photoAccessHelper** instance based on the application context. The instance obtained can be used to access or modify the media data (such as image and videos) in an album. The application needs to call [getPhotoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) to obtain a **PhotoAccessHelper** instance based on the application context. The instance obtained can be used to access or modify the media data (such as images and videos) in an album.
**How to Develop** **How to Develop**
1. Import the **photoAccessHelper** module. 1. Import the **photoAccessHelper** module.
2. Use **getContext** to obtain the application context. 2. Use **getContext** to obtain the application context.
3. Obtain a **photoAccessHelper** instance. 3. Obtain a **PhotoAccessHelper** instance.
```ts ```ts
import photoAccessHelper from '@ohos.file.photoAccessHelper'; import photoAccessHelper from '@ohos.file.photoAccessHelper';
// The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations. If the code is not added, an undefined error will be reported. // The phAccessHelper instance obtained here is a global object. By default, the object obtained here is used in subsequent operations in this document. If an undefined error is reported, add the code snippet here.
const context = getContext(this); const context = getContext(this);
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
``` ```
...@@ -59,16 +58,16 @@ Before applying for permission, ensure that the [basic principles for permission ...@@ -59,16 +58,16 @@ Before applying for permission, ensure that the [basic principles for permission
| Permission | Description | Authorization Mode | | Permission | Description | Authorization Mode |
| ------------------------------ | ------------------------------------------ | ---------- | | ------------------------------ | ------------------------------------------ | ---------- |
| ohos.permission.READ_IMAGEVIDEO | Allows an app to read image and video file information from a user's external storage.| user_grant | | ohos.permission.READ_IMAGEVIDEO | Allows an application to read image and video file information from a user's external storage.| user_grant |
| ohos.permission.WRITE_IMAGEVIDEO | Allows an app to read and write image and video file information on a user's external storage.| user_grant | | ohos.permission.WRITE_IMAGEVIDEO | Allows an application to read and write image and video file information on a user's external storage.| user_grant |
The required permissions must be authorized by the user (user_grant). You need to add the permissions in the **module.json5** file, and use [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted by the user. If yes, the application can access the data. Otherwise, a dialog box will be displayed to request user authorization. The required permissions must be authorized by the user (user_grant). After adding the permissions in the **module.json5** file, use [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check whether the required permissions are granted by the user. If yes, the application can access the data. Otherwise, a dialog box will be displayed to request user authorization.
> **NOTE**<br>Even if the user has granted the permission, the permission will still be checked before an API protected by the permission is called. The permission granted status should not be persisted, because the user can revoke the permission through the system application **Settings**. > **NOTE**<br>Even if the user has granted the permission, the permission will still be checked before an API protected by the permission is called. The permission granted status should not be persisted, because the user can revoke the permission through the system application **Settings**.
**How to Develop** **How to Develop**
1. Declare the permissions in the **module.json5** file.<br>Add **requestPermissions** under **module** in the file, and add the required permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md). 1. Declare the required permissions in the **module.json5** file.<br>Add **requestPermissions** under **module** in the file, and add the required permissions. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md).
```json ```json
{ {
...@@ -99,7 +98,7 @@ The required permissions must be authorized by the user (user_grant). You need t ...@@ -99,7 +98,7 @@ The required permissions must be authorized by the user (user_grant). You need t
} }
``` ```
2. Call **requestPermissionsFromUser** in the **onWindowStageCreate** callback of **Ability.ts** to check for the required permissions. If the permissions are not granted, display a dialog box to request user authorization dynamically. 2. Call **requestPermissionsFromUser** in the **onWindowStageCreate** callback of **Ability.ts** to check the required permissions. If the permissions are not granted, display a dialog box to request user authorization dynamically.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
......
# Media Asset Management # Managing Media Assets
Applications can call **photoAccessHelper** APIs to manage media assets (images and videos). Applications can call **photoAccessHelper** APIs to manage media assets (images and videos).
> **NOTE** > **NOTE**
> >
> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. > Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).<br>
> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. > By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
## Obtaining the Specified Media Assets ## Obtaining the Specified Media Assets
You can query media assets by media type, date, or album name. You can obtain media assets by media type, date, or album name.
Use [PhotoAccessHelper.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets) with the [FetchOptions](../reference/apis/js-apis-photoAccessHelper.md#fetchoptions) object to specify search criteria. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. Use [PhotoAccessHelper.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets) with the [FetchOptions](../reference/apis/js-apis-photoAccessHelper.md#fetchoptions) object to specify search criteria. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
...@@ -19,7 +19,7 @@ To obtain the object at the specified position (for example, the first, the last ...@@ -19,7 +19,7 @@ To obtain the object at the specified position (for example, the first, the last
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported. - The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported.
...@@ -29,7 +29,7 @@ Example: Obtain the image **test.jpg**. ...@@ -29,7 +29,7 @@ Example: Obtain the image **test.jpg**.
**How to Develop** **How to Develop**
Create a **FetchOptions** object and specify **test.jpg**. 1. Create a **FetchOptions** object and specify **test.jpg**.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
...@@ -42,7 +42,7 @@ let fetchOptions = { ...@@ -42,7 +42,7 @@ let fetchOptions = {
}; };
``` ```
Call **PhotoAccessHelper.getAssets** to obtain image assets. 2. Call **PhotoAccessHelper.getAssets** to obtain image assets.
```ts ```ts
try { try {
...@@ -55,7 +55,7 @@ try { ...@@ -55,7 +55,7 @@ try {
} }
``` ```
### Obtaining an Image or Video Asset by URI ### Obtaining an Image or Video by URI
Example: Obtain the image with the file URI **file://media/Photo/1**. Example: Obtain the image with the file URI **file://media/Photo/1**.
...@@ -86,7 +86,7 @@ try { ...@@ -86,7 +86,7 @@ try {
### Obtaining Images or Videos by Time ### Obtaining Images or Videos by Time
Example: Obtain the media assets added from 2022-06-01 to 2023-06-01. Example: Obtain the media assets added between 2022-06-01 and 2023-06-01.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
...@@ -96,7 +96,7 @@ let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // The val ...@@ -96,7 +96,7 @@ let startTime = Date.parse(new Date('2022-06-01').toString()) / 1000; // The val
let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time. let endTime = Date.parse(new Date('2023-06-01').toString()) / 1000; // The value of the end time is the number of seconds elapsed since the Epoch time.
let date_added = photoAccessHelper.PhotoKeys.DATE_ADDED; let date_added = photoAccessHelper.PhotoKeys.DATE_ADDED;
predicates.between(date_added, startTime, endTime); predicates.between(date_added, startTime, endTime);
predicates.orderByDesc(date_added); // The query results are sorted in descending order. predicates.orderByDesc(date_added); // Sort the obtained records in descending order.
let fetchOptions = { let fetchOptions = {
fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added. fetchColumns: [date_added], // The date_added attribute is not a default option and needs to be added.
predicates: predicates predicates: predicates
...@@ -123,7 +123,7 @@ Use [FileAsset.getThumbnail](../reference/apis/js-apis-photoAccessHelper.md#gett ...@@ -123,7 +123,7 @@ Use [FileAsset.getThumbnail](../reference/apis/js-apis-photoAccessHelper.md#gett
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
- The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported. - The [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) module is imported.
...@@ -169,10 +169,10 @@ Use [createAsset](../reference/apis/js-apis-photoAccessHelper.md#createasset) to ...@@ -169,10 +169,10 @@ Use [createAsset](../reference/apis/js-apis-photoAccessHelper.md#createasset) to
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission. - The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission.
### Creating an Image or Video Asset ### Creating an Image or Video
Example: Create an image asset. Example: Create an image asset.
...@@ -197,15 +197,15 @@ try { ...@@ -197,15 +197,15 @@ try {
## Renaming a Media Asset ## Renaming a Media Asset
Before renaming a file, use [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) to obtain the file.
Set the **FileAsset.displayName** attribute to modify the file name (including the file name extension) displayed. Set the **FileAsset.displayName** attribute to modify the file name (including the file name extension) displayed.
After the modification, use [FileAsset.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify) to update the modification to the database. After the modification, use [FileAsset.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify) to update the modification to the database.
Before renaming a file, use [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) to obtain the file.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions. - The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions.
Example: Rename the first file in the obtained image assets. Example: Rename the first file in the obtained image assets.
...@@ -246,11 +246,11 @@ try { ...@@ -246,11 +246,11 @@ try {
You can use [deleteAssets](../reference/apis/js-apis-photoAccessHelper.md#deleteassets) to move files to the trash. You can use [deleteAssets](../reference/apis/js-apis-photoAccessHelper.md#deleteassets) to move files to the trash.
The files moved to the trash will be retained for 30 days, and deleted permanently after 30 days. Before a file is deleted permanently from the trash, the user can restore it using the system application **File Manager** or **Gallery**. The files moved to the trash will be retained for 30 days, and deleted permanently after 30 days. Before a file is deleted permanently from the trash, the user can restore it using the system application **FileManager** or **Gallery**.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions. - The application has the **ohos.permission.WRITE_IMAGEVIDEO** and **ohos.permission.READ_IMAGEVIDEO** permissions.
Example: Move the first file in the result set to the trash. Example: Move the first file in the result set to the trash.
......
# System Album Management # Managing System Albums
The **photoAccessHelper** module provides APIs for managing system albums, including the **Favorites**, video album, and screenshot album. The **photoAccessHelper** module provides APIs for managing system albums, including the **Favorites**, **Videos**, **Screenshots**.
> **NOTE** > **NOTE**
> >
> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. > Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).<br>
> By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **PhotoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **PhotoAccessHelper** is not defined is reported. > By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **PhotoAccessHelper** is not defined is reported.
To ensure application running efficiency, most **photoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
## Favorites ## Favorites
The **Favorites** is a system album. When you favorite a photo or video, the photo or video is added to **Favorites**. When you favorite a photo or video, the photo or video is removed from **Favorites**. **Favorites** is a system album. Favoriting a photo or video adds the photo or video to **Favorites**; unfavoriting a photo or video removes the photo or video from **Favorites**.
### Obtaining a Favorites Object ### Obtaining a Favorites Object
...@@ -20,7 +20,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt ...@@ -20,7 +20,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop** **How to Develop**
...@@ -41,11 +41,11 @@ try { ...@@ -41,11 +41,11 @@ try {
### Favoriting an Image or Video ### Favoriting an Image or Video
Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to add images or videos to **Favorites**. Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to add an image or video to **Favorites**.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Favorite an image. Example: Favorite an image.
...@@ -54,7 +54,7 @@ Example: Favorite an image. ...@@ -54,7 +54,7 @@ Example: Favorite an image.
1. [Obtain media assets](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets). 1. [Obtain media assets](photoAccessHelper-resource-guidelines.md#obtaining-the-specified-media-assets).
2. Set **favoriteState** to **true** to favorite the image. 2. Set **favoriteState** to **true** to favorite the image.
3. Use **FileAsset.setFavorite** to add the image to **Favorites**. 3. Call **FileAsset.setFavorite** to add the image to **Favorites**.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
...@@ -83,7 +83,7 @@ try { ...@@ -83,7 +83,7 @@ try {
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
Example: Obtain an image from **Favorites**. Example: Obtain an image from **Favorites**.
...@@ -121,20 +121,20 @@ try { ...@@ -121,20 +121,20 @@ try {
### Unfavoriting an Image or Video ### Unfavoriting an Image or Video
Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to remove an image or video from **Favorites**. Use [setFavorite](../reference/apis/js-apis-photoAccessHelper.md#setfavorite) to remove images or videos from **Favorites**.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Unfavorite an image. Example: Unfavorite an image.
**How to Develop** **How to Develop**
1. [Obtain the image and videos in **Favorites**](#obtaining-images-and-videos-in-favorites). 1. [Obtain the images and videos in **Favorites**](#obtaining-images-and-videos-in-favorites).
2. Set **favoriteState** to **false**. 2. Set **favoriteState** to **false**.
3. Use **FileAsset.setFavorite** to remove the image from **Favorites**. 3. Call **FileAsset.setFavorite** to unfavorite an image or video.
```ts ```ts
...@@ -163,9 +163,9 @@ try { ...@@ -163,9 +163,9 @@ try {
} }
``` ```
## Video Album ## Videos
The video album is a system album. The media assets of the video type in user files are automatically added to the video album. **Videos** is a system album that holds media assets of the video type in user files.
### Obtaining a Video Album Object ### Obtaining a Video Album Object
...@@ -173,7 +173,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt ...@@ -173,7 +173,7 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop** **How to Develop**
...@@ -192,16 +192,16 @@ try { ...@@ -192,16 +192,16 @@ try {
} }
``` ```
### Obtaining Videos from the Video Album ### Obtaining a Video from Videos
[Obtain a video album object](#obtaining-a-video-album-object). Use [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain video assets in the video album. [Obtain a video album object](#obtaining-a-video-album-object), and use [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain video assets in **Videos**.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
Example: Obtain a video in the video album. Example: Obtain a video in **Videos**.
**How to Develop** **How to Develop**
...@@ -234,17 +234,17 @@ try { ...@@ -234,17 +234,17 @@ try {
} }
``` ```
## Screenshot Album ## Screenshots
The screenshot album is a system album. The user's screenshots and screen recording files are automatically added to this album. **Screenshots** is a system album that holds user's screenshots and screen recording files.
### Obtaining a Screenshot Album Object ### Obtaining a Screenshot Album Object
Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a screenshot album. Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obtain a screenshot album object.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
**How to Develop** **How to Develop**
...@@ -263,16 +263,16 @@ try { ...@@ -263,16 +263,16 @@ try {
} }
``` ```
### Obtaining Media Assets in the Screenshot Album ### Obtaining Media Assets in Screenshots
[Obtain a screenshot album object](#obtaining-a-screenshot-album-object), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the album. [Obtain a screenshot album object](#obtaining-a-screenshot-album-object), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the album.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
Example: Obtain a media asset from the screenshot album. Example: Obtain a media asset from **Screenshots**.
**How to Develop** **How to Develop**
......
# User Album Management # Managing User Albums
The **photoAccessHelper** module provides APIs for user album management, including creating or deleting a user album, adding images and videos to a user album, and deleting image and videos from a user album. The **photoAccessHelper** module provides APIs for user album management, including creating or deleting a user album, adding images and videos to a user album, and deleting image and videos from a user album.
> **NOTE** > **NOTE**
> >
> Before you start, refer to [photoAccessHelper Overview](photoAccessHelper-overview.md) to learn how to obtain a **photoAccessHelper** instance and apply for permissions required. > Before you start, you need to obtain a **PhotoAccessHelper** instance and apply for required permissions. For details, see [photoAccessHelper Overview](photoAccessHelper-overview.md).<br>
> By default, the **photoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **photoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported. > By default, the **PhotoAccessHelper** instance obtained in [photoAccessHelper Overview](photoAccessHelper-overview.md) is used when **photoAccessHelper** APIs are used. If the code for obtaining the **PhotoAccessHelper** instance is not added, an error indicating that **photoAccessHelper** is not defined is reported.
To ensure application running efficiency, most **PhotoAccessHelper** calls are asynchronous in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md). To ensure application running efficiency, most **photoAccessHelper** APIs are asynchronously implemented in callback or promise mode. The following code samples use promise-based APIs. For details about the APIs, see [Album Management](../reference/apis/js-apis-photoAccessHelper.md).
Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database. Unless otherwise specified, all the media assets to be obtained in this document exist in the database. If no media asset is obtained when the sample code is executed, check whether the media assets exist in the database.
## Creating a User Album ## Creating a User Album
...@@ -23,14 +23,14 @@ The album name must meet the following requirements: ...@@ -23,14 +23,14 @@ The album name must meet the following requirements:
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission. - The application has the **ohos.permission.WRITE_IMAGEVIDEO** permission.
Example: Create a user album. Example: Create a user album.
**How to Develop** **How to Develop**
1. Set the name of the album to create. 1. Set the name of the album.
2. Use **createAlbum** to create an album. 2. Use **createAlbum** to create an album.
```ts ```ts
...@@ -49,10 +49,10 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt ...@@ -49,10 +49,10 @@ Use [getAlbums](../reference/apis/js-apis-photoAccessHelper.md#getalbums) to obt
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** permission. - The application has the **ohos.permission.READ_IMAGEVIDEO** permission.
Example: Obtain a user album named **albumName**. Example: Obtain the user album named **albumName**.
**How to Develop** **How to Develop**
...@@ -83,17 +83,15 @@ try { ...@@ -83,17 +83,15 @@ try {
## Renaming a User Album ## Renaming a User Album
Modify the **Albums.albumName** attribute of the album, Modify the **Albums.albumName** attribute of the album, and use [Album.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify-2) to update the modification to the database.
and use [Album.commitModify](../reference/apis/js-apis-photoAccessHelper.md#commitmodify-2) to update the modification to the database. Before renaming a user album, you need to obtain an album object. You can use the [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) APIs to obtain the user album of the specified location.
Before renaming a user album, you need to obtain an album object. You can use the [FetchResult](../reference/apis/js-apis-photoAccessHelper.md#fetchresult) APIs to obtain the user album of the corresponding location.
The new user album names must also comply with the user name requirements in [Creating a User Album](#creating-a-user-album). The new user album names must also comply with the user name requirements in [Creating a User Album](#creating-a-user-album).
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Rename an album named **albumName**. Example: Rename an album named **albumName**.
...@@ -104,7 +102,7 @@ Example: Rename an album named **albumName**. ...@@ -104,7 +102,7 @@ Example: Rename an album named **albumName**.
2. Call **getAlbums** to obtain user albums. 2. Call **getAlbums** to obtain user albums.
3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album. 3. Call [FetchResult.getFirstObject](../reference/apis/js-apis-photoAccessHelper.md#getfirstobject) to obtain the first user album.
4. Set a new album name. 4. Set a new album name.
5. Call **Album.commitModify** to update the modified album attributes to the database. 5. Call **Album.commitModify** to update the new album name to the database.
```ts ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
...@@ -129,16 +127,16 @@ try { ...@@ -129,16 +127,16 @@ try {
} }
``` ```
## Adding Images and Videos to a User Album ## Adding Images or Videos to a User Album
[Obtain a user album](#obtaining-a-user-album) and the array of the images or videos to be added to the album, and then call [Album.addAssets](../reference/apis/js-apis-photoAccessHelper.md#addassets) to add the images or videos to the user album. [Obtain the user album](#obtaining-a-user-album) and the images or videos to be added to the album, and then call [Album.addAssets](../reference/apis/js-apis-photoAccessHelper.md#addassets) to add the images or videos to the user album.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Add an image to the album named **albumName**. Example: Add an image to the album **albumName**.
**How to Develop** **How to Develop**
...@@ -184,14 +182,14 @@ try { ...@@ -184,14 +182,14 @@ try {
## Obtaining Images and Videos in a User Album ## Obtaining Images and Videos in a User Album
[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album. [Obtain the user album](#obtaining-a-user-album), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Obtain an image in a user album named **albumName**. Example: Obtain an image in the user album **albumName**.
**How to Develop** **How to Develop**
...@@ -235,13 +233,13 @@ try { ...@@ -235,13 +233,13 @@ try {
## Removing Images and Videos from a User Album ## Removing Images and Videos from a User Album
[Obtain the user album](#obtaining-a-user-album) object, and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album. [Obtain the user album](#obtaining-a-user-album), and call [Album.getAssets](../reference/apis/js-apis-photoAccessHelper.md#getassets-2) to obtain the media assets in the user album.
Use [Album.removeAssets](../reference/apis/js-apis-photoAccessHelper.md#removeassets) to remove the specified images. Use [Album.removeAssets](../reference/apis/js-apis-photoAccessHelper.md#removeassets) to remove the specified media assets.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Remove an image from the album named **albumName**. Example: Remove an image from the album named **albumName**.
...@@ -290,11 +288,11 @@ try { ...@@ -290,11 +288,11 @@ try {
## Deleting a User Album ## Deleting a User Album
[Obtain the user album](#obtaining-a-user-album) object, and call [deleteAlbums](../reference/apis/js-apis-photoAccessHelper.md#deletealbums) to delete the user album. [Obtain the user album](##obtaining-a-user-album), and call [deleteAlbums](../reference/apis/js-apis-photoAccessHelper.md#deletealbums) to delete the user album.
**Prerequisites** **Prerequisites**
- A **photoAccessHelper** instance is obtained. - A **PhotoAccessHelper** instance is obtained.
- The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions. - The application has the **ohos.permission.READ_IMAGEVIDEO** and **ohos.permission.WRITE_IMAGEVIDEO** permissions.
Example: Delete a user album named **albumName**. Example: Delete a user album named **albumName**.
......
...@@ -2,16 +2,16 @@ ...@@ -2,16 +2,16 @@
When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file. When a user needs to download a file from the network to a local directory or save a user file into another directory, use **FilePicker** to save the file.
The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if **FilePicker** is used to access files. The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding picker instance and pass in **saveOptions**. No permission is required if your application uses **FilePicker** to access files.
The **save()** method saves the file in the file manager, not in the Gallery. The **save()** method saves files in the file manager, not in **Gallery**.
## Saving Images or Video Files ## Saving Images or Video Files
For example, select an image from **Gallery** and save it to the file manager. For example, select an image from **Gallery** and save it to the file manager.
1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates](../reference/apis/js-apis-data-dataSharePredicates.md) modules. 1. Import the [picker](../reference/apis/js-apis-file-picker.md), [fs](../reference/apis/js-apis-file-fs.md), [photoAccessHelper](../reference/apis/js-apis-photoAccessHelper.md), and [dataSharePredicates] (../reference/apis/js-apis-data-dataSharePredicates.md) modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -53,9 +53,9 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -53,9 +53,9 @@ For example, select an image from **Gallery** and save it to the file manager.
} }
``` ```
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the image. After the user selects the target folder, the file saving operation is complete. After the image is saved successfully, the URI of the saved image is returned. 3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) to open the **FilePicker** page to save the image. After the user selects the destination folder, the image is saved and the URI of the saved image is returned.
The permission on the URI returned by **save()** is read/write. Further operations can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri:string; let uri:string;
...@@ -81,9 +81,9 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -81,9 +81,9 @@ For example, select an image from **Gallery** and save it to the file manager.
} }
``` ```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. 4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
Use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to edit and modify the file based on the FD. After the modification is complete, close the FD. Then, use [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to modify the file based on the FD, and close the FD after the modification is complete.
```ts ```ts
async writeOnly(uri) { async writeOnly(uri) {
...@@ -100,7 +100,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -100,7 +100,7 @@ For example, select an image from **Gallery** and save it to the file manager.
## Saving Documents ## Saving Documents
1. Import the **picker** module and **fs** module. 1. Import the **picker** and **fs** modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -111,12 +111,12 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -111,12 +111,12 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts ```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance. const documentSaveOptions = new picker.DocumentSaveOptions(); // Create a documentSaveOptions instance.
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents to save. documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the name of the document to save.
``` ```
3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the documents. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned. 3. Create a **documentViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-3) to open the **FilePicker** page to save the document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri = null; let uri = null;
...@@ -129,14 +129,14 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -129,14 +129,14 @@ For example, select an image from **Gallery** and save it to the file manager.
}) })
``` ```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. 4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts ```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
console.info('file fd: ' + file.fd); console.info('file fd: ' + file.fd);
``` ```
5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the file based on the FD, and then close the FD. 5. Use [fs.writeSync()](../reference/apis/js-apis-file-fs.md#writesync) to edit the document based on the FD, and then close the FD.
```ts ```ts
let writeLen = fs.writeSync(file.fd, 'hello, world'); let writeLen = fs.writeSync(file.fd, 'hello, world');
...@@ -146,7 +146,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -146,7 +146,7 @@ For example, select an image from **Gallery** and save it to the file manager.
## Saving Audio Files ## Saving Audio Files
1. Import the **picker** module and **fs** module. 1. Import the **picker** and **fs** modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -157,12 +157,12 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -157,12 +157,12 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts ```ts
const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance. const audioSaveOptions = new picker.AudioSaveOptions(); // Create an audioSaveOptions instance.
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files to save. audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the name of the audio file to save.
``` ```
3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the files. After the user selects the target folder, the file saving operation is complete. After the files are saved successfully, the URIs of the files saved are returned. 3. Create an **audioViewPicker** instance, and call [save()](../reference/apis/js-apis-file-picker.md#save-6) to open the **FilePicker** page to save the file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is returned.
The permission on the URIs returned by **save()** is read/write. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URI returned by **save()** is read/write. Further operations on the file can be performed based on the URI in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
```ts ```ts
let uri = null; let uri = null;
...@@ -175,7 +175,7 @@ For example, select an image from **Gallery** and save it to the file manager. ...@@ -175,7 +175,7 @@ For example, select an image from **Gallery** and save it to the file manager.
}) })
``` ```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**. 4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_WRITE**.
```ts ```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
......
# Selecting User Files # Selecting User Files
If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files. If your application needs to support share and saving of user files (such as images and videos), you can use OpenHarmony [FilePicker](../reference/apis/js-apis-file-picker.md) to implement selection and saving of user files. No permission is required if your application uses **FilePicker** to access files.
The **FilePicker** provides the following interfaces by file type: The **FilePicker** provides the following interfaces by file type:
- [**PhotoViewPicker**](../reference/apis/js-apis-file-picker.md#photoviewpicker): used to select and save images or video files. - [PhotoViewPicker](../reference/apis/js-apis-file-picker.md#photoviewpicker): used to select and save images or video files.
- [**DocumentViewPicker**](../reference/apis/js-apis-file-picker.md#documentviewpicker): used to select and save documents. - [DocumentViewPicker](../reference/apis/js-apis-file-picker.md#documentviewpicker): used to select and save documents.
- [**AudioViewPicker**](../reference/apis/js-apis-file-picker.md#audioviewpicker): used to select and save audio files. - [AudioViewPicker](../reference/apis/js-apis-file-picker.md#audioviewpicker): used to select and save audio files.
## Selecting Images or Video Files ## Selecting Images or Video Files
1. Import the **picker** module and **fs** module. 1. Import the **picker** and **fs** modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -25,8 +25,8 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -25,8 +25,8 @@ The **FilePicker** provides the following interfaces by file type:
const photoSelectOptions = new picker.PhotoSelectOptions(); const photoSelectOptions = new picker.PhotoSelectOptions();
``` ```
3. Set the file type and the maximum number of media files to select. 3. Set the file type and the maximum number of media files to select.<br>
For example, select a maximum of five images. For details about the media file type, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes). For example, select a maximum of five images. For details about the media file types, see [PhotoViewMIMETypes](../reference/apis/js-apis-file-picker.md#photoviewmimetypes).
```ts ```ts
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // Select images. photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // Select images.
...@@ -48,14 +48,14 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -48,14 +48,14 @@ The **FilePicker** provides the following interfaces by file type:
}) })
``` ```
5. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. 5. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the file descriptor (FD). Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts ```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd); console.info('file fd: ' + file.fd);
``` ```
6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD. 6. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts ```ts
let buffer = new ArrayBuffer(4096); let buffer = new ArrayBuffer(4096);
...@@ -66,7 +66,7 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -66,7 +66,7 @@ The **FilePicker** provides the following interfaces by file type:
## Selecting Documents ## Selecting Documents
1. Import the **picker** module and **fs** module. 1. Import the **picker** and **fs** modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -83,7 +83,7 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -83,7 +83,7 @@ The **FilePicker** provides the following interfaces by file type:
The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening. The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the result set. Note that the URI cannot be directly used in the **picker** callback to open a file. You need to define a global variable to save the URI and use a button to trigger file opening.
For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attribute information, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md). For example, you can use [file management APIs](../reference/apis/js-apis-file-fs.md) to obtain file attributes, such as the file size, access time, and last modification time, based on the URI. If you need to obtain the file name, use [startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md).
> **NOTE** > **NOTE**
> >
...@@ -102,7 +102,7 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -102,7 +102,7 @@ The **FilePicker** provides the following interfaces by file type:
> **NOTE** > **NOTE**
> >
> Currently, **DocumentSelectOptions** does not provide the method for obtaining the file name. To obtain the file name, use **startAbilityForResult()**. > Currently, **DocumentSelectOptions** cannot be used to obtain the file name. To obtain the file name, use **startAbilityForResult()**.
```ts ```ts
let config = { let config = {
...@@ -126,14 +126,14 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -126,14 +126,14 @@ The **FilePicker** provides the following interfaces by file type:
} }
``` ```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. 4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts ```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd); console.info('file fd: ' + file.fd);
``` ```
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD. 5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts ```ts
let buffer = new ArrayBuffer(4096); let buffer = new ArrayBuffer(4096);
...@@ -143,9 +143,9 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -143,9 +143,9 @@ The **FilePicker** provides the following interfaces by file type:
``` ```
## Selecting an Audio File ## Selecting Audio Files
1. Import the **picker** module and **fs** module. 1. Import the **picker** and **fs** modules.
```ts ```ts
import picker from '@ohos.file.picker'; import picker from '@ohos.file.picker';
...@@ -179,14 +179,14 @@ The **FilePicker** provides the following interfaces by file type: ...@@ -179,14 +179,14 @@ The **FilePicker** provides the following interfaces by file type:
}) })
``` ```
4. Use a button to trigger invocation of other functions. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**. 4. After the UI is returned from the **FilePicker** page, use a button to trigger API calling. Use [fs.openSync()](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD. Note that the **mode** parameter of **fs.openSync()** must be **fs.OpenMode.READ_ONLY**.
```ts ```ts
let file = fs.openSync(uri, fs.OpenMode.READ_ONLY); let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd); console.info('file fd: ' + file.fd);
``` ```
5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file data based on the FD. After the data is read, close the FD. 5. Use [fs.readSync()](../reference/apis/js-apis-file-fs.md#readsync) to read the file based on the FD. After the data is read, close the FD.
```ts ```ts
let buffer = new ArrayBuffer(4096); let buffer = new ArrayBuffer(4096);
......
# Sending Files to an Application Sandbox # Pushing Files to an Application Sandbox
During the development and debugging process of an application, you may need to place some files to the application sandbox for intra-application access or for testing purposes. In this case, you can use either of the following methods: During the development and debugging process of an application, you may need to push files to the application sandbox for intra-application access or for testing purposes. In this case, you can use either of the following methods:
1. Use DevEco Studio to place the files to the application installation directory. For details, see [Application Installation Resource Access](../quick-start/resource-categories-and-access.md# resource-access). - Use DevEco Studio to push the files to the application installation directory. For details, see [Application Installation Resource Access](../quick-start/resource-categories-and-access.md#resource-access).
2. Use the hdc tool to send files to the application sandbox directory on the device. This section describes the second method. - Use the hdc tool to push files to the application sandbox directory on the device. This section describes the second method.
However, the file directories visible to the debugged process in the hdc shell are different from the application sandbox directories visible to the application. You need to understand the mappings between the application sandbox directories and the physical (real) directories. However, the file directories visible to the debugged process in the hdc shell are different from the application sandbox directories visible to the application. You need to understand the mappings between the application sandbox directories and the physical (real) directories.
...@@ -27,15 +27,15 @@ The read and write operations performed based on the application sandbox paths v ...@@ -27,15 +27,15 @@ The read and write operations performed based on the application sandbox paths v
The following uses the application bundle **com.ohos.example** as an example. If the application sandbox path is **/data/storage/el1/bundle**, the physical path is **/data/app/el1/bundle/public/<PACKAGENAME>**, that is, **/data/app/el1/bundle/public/com.ohos.example**. The following uses the application bundle **com.ohos.example** as an example. If the application sandbox path is **/data/storage/el1/bundle**, the physical path is **/data/app/el1/bundle/public/<PACKAGENAME>**, that is, **/data/app/el1/bundle/public/com.ohos.example**.
Run the following command to send the file: Run the following command to push files:
``` ```
hdc file send ${Path of the local file to send} /data/app/el1/bundle/public/com.ohos.example/ hdc file send ${Path of the local files to send} /data/app/el1/bundle/public/com.ohos.example/
``` ```
## Switching to the Application View ## Switching to the Application View
During the debugging process, if you do not have the permission or the file does not exist, you need to switch from the process view to the application view and further analyze permission and directory problems. To switch to the application view, run the following commands: During the debugging process, if the required permission is unavailable or the file does not exist, you need to switch from the process view to the application view and further analyze permission and directory problems. To switch to the application view, run the following commands:
``` ```
hdc shell // Switch to shell. hdc shell // Switch to shell.
......
# Setting the Security Level of a Distributed File # Setting the Security Level of a Distributed File
The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of standards for data and device classification and custom data transfer policies for different devices. For details, see [Data Security Labels and Device Security Levels](../database/access-control-by-device-and-data-level.md). The security capabilities vary with devices. For example, small embedded devices provide fewer security capabilities than tablets. The security requirements also vary with data. For example, personal health information and bank card information are not expected to be accessed by devices of lower security levels. OpenHarmony provides a complete set of data and device classification standards and custom data transfer policies for different devices. For details, see [Access Control by Device and Data Level](../database/access-control-by-device-and-data-level.md).
## Available APIs ## Available APIs
...@@ -8,26 +8,26 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a ...@@ -8,26 +8,26 @@ For details about the APIs, see [ohos.file.securityLabel](../reference/apis/js-a
**Table 1** APIs **Table 1** APIs
| API| Description| Type| Synchronous Programming| Asynchronous Programming| | API| Description| Type| Synchronous Programming| Asynchronous Programming|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| setSecurityLabel | Sets a security label for a file.| Method| √ | √ | | setSecurityLabel | Sets a security label for a file.| Method| √ | √ |
| getSecurityLabel | Obtains the security label of a file.| Method| √ | √ | | getSecurityLabel | Obtains the security label of a file.| Method| √ | √ |
> **NOTICE** > **NOTE**
> >
> 1. In distributed networking, a device can view the files that do not match its security level but cannot access them. > - In distributed networking, a device can view the files that do not match its security level but cannot access them.
> >
> 2. The default security level of the distributed file system data is S3. Applications can set the security level of files. > - The default security level of the distributed file system data is S3. Applications can set the security level of files.
## Development Example ## Development Example
Obtain the sandbox path of the file and set the data security label. For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). Obtain the sandbox path of a file and set the data security label. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
import securityLabel from '@ohos.file.securityLabel'; import securityLabel from '@ohos.file.securityLabel';
//Obtain the sandbox path of the file. // Obtain the sandbox path of the file.
let context =...; // Obtain UIAbilityContext information. let context =...; // Obtain UIAbilityContext information.
let pathDir = context.filesDir; let pathDir = context.filesDir;
let filePath = pathDir + '/test.txt'; let filePath = pathDir + '/test.txt';
......
# Sharing an Application File # Sharing an Application File
The file of an application can be shared with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. However, if the FD of a shared file is closed, the file cannot be opened. Therefore, the file sharing based on the FD is not recommended. This section describes how to share an application file based on its URI. An application can share its file with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. However, if the FD of a shared file is closed, the file is no longer opened. Therefore, the FD-based file sharing is not recommended. This section describes how to share an application file based on its URI.
- You can use **wantConstant.Flags()** of the [ohos.app.ability.wantConstant](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantflags) module to share an application file in read or read/write mode based on its URI with another application. The target application can use **open()** of the [ohos.file.fs](../reference/apis/js-apis-file-fs.md#fsopen) module to open the URI and then perform read and/or write operations based on the permissions granted. Currently, OpenHarmony API version 9 supports only temporary authorization. The permission on shared file is revoked once the target application exits. - You can use [wantConstant.Flags](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantflags) to share a single application file in read or read/write mode based on its URI with another application. The target application can use **open()** of the [ohos.file.fs](../reference/apis/js-apis-file-fs.md#fsopen) module to open the URI and then perform read and/or write operations based on the permissions granted. OpenHarmony API version 9 supports only temporary authorization. The permission on the shared file is revoked once the target application exits.
- You can also use **open()** of the ohos.file.fs module to share an application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs. - You can also use **open()** of the ohos.file.fs module to share a single application file with the specified permissions to another application based on the FD. After parsing the FD from **Want**, the target application can read and write the file by using **read()** and **write()** APIs of ohos.file.fs.
You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-files). You can use the related APIs to [share a file with another application](#sharing-a-file-with-another-application) or [use shared application files](#using-shared-files).
...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing ...@@ -12,7 +12,7 @@ You can use the related APIs to [share a file with another application](#sharing
The file URIs are in the following format: The file URIs are in the following format:
file://&lt;bundleName&gt;/&lt;path&gt; **file**://&lt;*bundleName*&gt;/&lt;*path*&gt;
- **file**: indicates a file URI. - **file**: indicates a file URI.
...@@ -22,7 +22,7 @@ The file URIs are in the following format: ...@@ -22,7 +22,7 @@ The file URIs are in the following format:
## Sharing a File with Another Application ## Sharing a File with Another Application
Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-the-application-development-path). Before sharing application files, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-application-file-paths).
1. Obtain the application sandbox path of the file and convert it into the file URI. 1. Obtain the application sandbox path of the file and convert it into the file URI.
...@@ -43,7 +43,7 @@ Before sharing application files, you need to [obtain the application file path] ...@@ -43,7 +43,7 @@ Before sharing application files, you need to [obtain the application file path]
``` ```
2. Set the target application, with which you want to share the file, and grant permissions on the file. 2. Set the target application, with which you want to share the file, and grant permissions on the file.
Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the URI obtained in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes). Use [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to share the file with the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis/js-apis-app-ability-want.md#attributes).
> **NOTE** > **NOTE**
> >
...@@ -85,7 +85,7 @@ Before sharing application files, you need to [obtain the application file path] ...@@ -85,7 +85,7 @@ Before sharing application files, you need to [obtain the application file path]
## Using Shared Files ## Using Shared Files
In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**. In the [**module.json5** file](../quick-start/module-configuration-file.md) of the application, which wants to use the shared file, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by another application and set **uris** to the type of the URI to receive. In the following example, the application receives only .txt files with **scheme** of **file**.
```json ```json
{ {
"module": { "module": {
...@@ -115,7 +115,7 @@ In the [**module.json5** file](../quick-start/module-configuration-file.md) of t ...@@ -115,7 +115,7 @@ In the [**module.json5** file](../quick-start/module-configuration-file.md) of t
After **UIAbility** of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). After **UIAbility** of the application starts, the application obtains **want** information from [**onCreate()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [**onNewWant()**](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant).
After obtaining the URI of the shared file through **want**, the application can call **fs.open()** to open the file, and then read and write the file after obtaining the related file object. After obtaining the URI of the shared file from **want**, the application can call **fs.open()** to open the file, and then read and write the file after obtaining the related file object.
```ts ```ts
// xxx.ets // xxx.ets
......
# User File Overview # User File Overview
User files are the private images, video and audio clips, and documents of the user who logs in to the device. User files are the private images, video and audio clips, and documents of the user who has logged in to the device.
1. User files are stored in a directory, whose owner is the user who logs in to the device. - User files are stored in a directory, whose owner is the user who has logged in to the device.
2. User files can be stored in [built-in storage](#built-in-storage) and [external storage](#external-storage). - User files can be stored in [built-in storage](#built-in-storage) and [external storage](#external-storage) of the device.
3. An application cannot access user files without user authorization, or the operations on user files must be performed by the user. - An application cannot access user files without user authorization, or the operations on user files must be performed by the user.
OpenHarmony provides the [user file access framework](#user-file-access-framework) for developers to access and manage user files, which will be described in detail below. OpenHarmony provides the [user file access framework](#user-file-access-framework) for developers to access and manage user files.
## User File Storage ## User File Storage
### Built-in Storage ### Built-in Storage
Built-in storage refers to the internal storage device (space) of a device. The built-in storage device cannot be removed. The following files can be stored in the built-in storage of a device: Built-in storage is the internal storage device (space) of a device. The built-in storage device cannot be removed. The following files can be stored in the built-in storage of a device:
- Files owned by a user: The files belong to the user who logs in to the device. Different users who log in to a device can view only their own files. - Files of a user: The files belong to the user who has logged in to the device. Different login users on a device can view their own files only.
These user files can be classified into the following types based on file attributes and access habits of users/applications: These user files can be classified into the following types based on file attributes and access habits of users/applications:
- Image/Video files - Image/Video files<br>
The files have attributes, such as the shooting time, location, rotation angle, and file width and height information, and are stored in media file formats. The files are usually presented as media files or albums, without the specific location in the system. The files have attributes, such as the shooting time, location, rotation angle, and file width and height information, and are stored in media file formats. Generally, these files are presented as media files or albums, without the specific storage location in the system.
- Audio files - Audio files<br>
The files have attributes, such as the album, creator, and shooting duration information, and are stored in media file formats. Generally, the files are presented by file, album, or creator, without the specific location in the system. The files have attributes, such as the album, artist, and duration information, and are stored in media file formats. Generally, audio files are presented by file, album, or artist, without the specific storage location in the system.
- Documents - Other files (documents)<br>
The files are stored as common files, including common text files, compressed files, and images, videos and audio clips stored as common files. These files are presented in a directory tree. The files are stored as common files, including common text files, compressed files, and images, videos and audio clips stored as common files. Generally, these files are presented in a directory tree.
- Files shared by users: The files are stored in a directory for share and shared by multiple users. - Files shared by users: The files are stored in a share directory to enable access from multiple users.
The files in the shared directory are stored as common files and presented in a directory tree. The files in the share directory are stored as common files and presented in a directory tree.
### External Storage ### External Storage
External storage is not inside a device's main storage or memory. Common external storage devices include pluggable devices, such as SD cards and USB flash drives. Same as the files in the shared directory of the built-in storage device, the files in an external storage device can be viewed by all the users who log in to the system. External storage is not inside a device's main storage or memory. Common external storage devices include pluggable devices, such as SD cards and USB flash drives. Same as the files in the share directory of the built-in storage device, the files in an external storage device can be viewed by all the users who has logged in to the system.
External storage devices are pluggable. OpenHarmony provides the functions of listening for the device insertion and removal events and mounting/unmounting an external storage device. For details, see [Managing External Storage Devices)](manage-external-storage.md). External storage devices are pluggable. OpenHarmony provides listening for the device insertion/removal events and mount/unmount of an external storage device. For details, see [Managing External Storage Devices](manage-external-storage.md).
The files on external storage devices are presented as common files in a directory tree, like the documents stored in built-in storage. The files on external storage devices are presented as common files in a directory tree, like the documents in built-in storage.
## User File Access Framework ## User File Access Framework
OpenHarmony provides the user file access framework for developers to access and manage user files. This framework leverages the ExtensionAbility of OpenHarmony to provide a set of methods and interfaces for accessing user files. OpenHarmony provides the user file access framework for developers to access and manage user files. This framework leverages the ExtensionAbility of OpenHarmony to provide a set of methods and interfaces for accessing user files.
**Figure 1** User file access framework **Figure 1** User file access framework
![User file access framework](figures/user-file-access-framework.png) ![User file access framework](figures/user-file-access-framework.png)
- To access user files, for example, select a photo or save multiple documents, a system application or third-party application (file access client in **Figure 1**) starts the **FilePicker** application. - The file access client (a system application or third-party application) can access user files, for example, select a photo or save multiple documents, by starting the **FilePicker** application.
- OpenHarmony is prebuilt with the **FilePicker** and **FileManager** applications. - OpenHarmony is prebuilt with the **FilePicker** and **FileManager** applications.
- **FilePicker**: provides APIs for a file access client to select and save user files without any permission. For details, see [Selecting User Files](select-user-file.md). - **FilePicker**: allows a file access client to select and save user files without any permission. For details, see [Selecting User Files](select-user-file.md).
- **FileManager**: allows users to view and modify files, and delete, rename, move, and create files or directories by using a system FileManager. - **FileManager**: allows users to view and modify files, and delete, rename, move, and create files or directories.
You can also develop your own FilePicker or FileManager applications as required. FilePicker is a subset of FileManager. For details about how to develop a FileManager application, see [Developing a FileManager Application)](dev-user-file-manager.md). You can also develop your own file picker or file manager applications as required. File picker is a subset of file manager. For details about how to develop a file manager application, see [Developing a File Manager Application](dev-user-file-manager.md).
- The user file access framework provides the following functional modules: - The user file access framework consists of the following functional modules:
- **File Access Helper**: provides APIs for the **FileManager** and **FilePicker** to access user files. - **File Access Helper**: provides APIs for the **FileManager** and **FilePicker** to access user files.
- **File Access ExtensionAbility**: provides a file access framework to implement file access functions. The **File Access ExtensionAbility** consists of the following: - **File Access ExtensionAbility**: implements file access via the following services:
- **UserFileManager**: implements management of the files stored on the built-in storage. - **UserFileManager**: implements management of the files on the built-in storage based on the File Access ExtensionAbility framework.
- **ExternalFileManager**: implements management of the files stored on the external storage. - **ExternalFileManager**: implements management of the files on the external storage based on the File Access ExtensionAbility framework.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册