提交 22452aae 编写于 作者: A Annie_wang

update docs

Signed-off-by: NAnnie_wang <annie.wangli@huawei.com>
上级 b8e098dc
......@@ -19,3 +19,94 @@ When the hdc command is used to send a file to a device, "permission denied" is
**Solution**
Run the **hdc shell mount -o remount,rw /** command to grant the read/write permissions.
## What is the best way to create a file if the file to open does not exist?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Use **fs.open(path: string, mode?: number)** with **mode** set to **fs.OpenMode.CREATE**. **fs.OpenMode.CREATE** creates a file if it does not exist.
## How do I solve the problem of garbled Chinese characters in a file?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
After the buffer data of the file content is read, use **TextDecoder** of @ohos.util to decode the file content.
```
let filePath = getContext(this).filesDir + "/test0.txt";
let stream = fs.createStreamSync(filePath, "r+");
let buffer = new ArrayBuffer(4096)
let readOut = stream.readSync(buffer);
let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true })
let readString = textDecoder.decodeWithStream(new Uint8Array(buffer), { stream: false });
console.log ("File content read: "+ readString);
```
## Why is an error reported when **fs.copyFile** is used to copy a **datashare://** file opened by **fs.open()**?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
**fs.copyFile** does not support URIs. You can use **fs.open()** to obtain the URI, obtain the file descriptor (FD) based on the URI, and then use **fs.copyFile** to copy the file based on the FD.
```
let file = fs.openSync("datashare://...")
fs.copyFile(file.fd, 'dstPath', 0).then(() => {
console.info('copyFile success')
}).catch((err) => {
console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
})
```
## How do I modify the specified content of a JSON file in the sandbox?
Applicable to: OpenHarmony 3.2 (API version 9)
**Solution**
Perform the following steps:
1. Use **fs.openSyn** to obtain the FD of the JSON file.
```
import fs from '@ohos.file.fs';
let sanFile = fs.open(basePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let fd = sanFile.fd;
```
2. Use **fs.readSync** to read the file content.
```
let content = fs.readSync(basePath);
```
3. Modify the file content.
```
obj.name = 'new name';
```
4. Write the JSON file again.
```
fs.writeSync(file.fd, JSON.stringify(obj));
```
For more information, see [@ohos.file.fs](../reference/apis/js-apis-file-fs.md).
## What is the actual path corresponding to the file path obtained through the FileAccess module?
Applicable to: OpenHarmony 3.2 (API version 9, stage model)
**Solution**
The files are stored in the **/storage/media/100/local/files** directory. The specific file path varies with the file type and source. To obtain the actual file path, run the following command in the **/storage/media/100/local/files** directory:
**-name \[filename\]**
For more information, see [Uploading and Downloading an Application File](../file-management/app-file-upload-download.md).
......@@ -10,6 +10,10 @@
- [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md)
- [Sending Files to an Application Sandbox](send-file-to-app-sandbox.md)
- [Sharing an Application File](share-app-file.md)
- Application Data Backup and Restoration
- [Application Data Backup and Restoration Overview](app-file-backup-overview.md)
- [Backing Up and Restoring Application Access Data](app-file-backup-extension.md)
- [Backing Up and Restoring Application-triggered Data (for System Applications Only)](app-file-backup.md)
- User File
- [User File Overview](user-file-overview.md)
- Selecting and Saving User Files (FilePicker)
......
# Backing Up and Restoring Application Access Data
You can use BackupExtensionAbility to implement backup and restoration of application access data.
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.
## Constraints
- 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 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.
## How to Develop
1. Add the **extensionAbilities** configuration in 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).
BackupExtensionAbility configuration example:
```json
{
"extensionAbilities": [
{
"description": "$string:ServiceExtAbility",
"icon": "$media:icon",
"name": "BackupExtensionAbility",
"type": "backup",
"visible": true,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
"srcEntrance": "",
}
]
}
```
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.
Metadata resource configuration file example:
```json
{
"allowToBackupRestore": true,
"includes": [
"/data/storage/el2/base/files/users/*/*.json"
],
"excludes": [
"/data/storage/el2/base/files/users/*/hidden.json"
],
}
```
### Description of the Metadata Resource Configuration File
| Name | Type | Mandatory| Description |
| -------------------- | ---------- | ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 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).|
| 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. |
**includes** default value:
```json
{
"includes": [
"data/storage/el2/database/",
"data/storage/el2/base/files/",
"data/storage/el2/base/preferences/",
"data/storage/el2/base/haps/*/database/",
"data/storage/el2/base/haps/*/base/files/",
"data/storage/el2/base/haps/*/base/preferences/",
]
}
```
# 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.
Before development, you need to understand the ExtensionAbility component. For details, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md).
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.
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.
Applications can perform backup and restoration configurations, but not 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.
# Backing Up and Restoring Application-triggered Data (for System Applications Only)
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:
- [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.
- [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.
- [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.
- [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.
## How to Develop
For details about the APIs to be used, see [Backup and Restoration](../reference/apis/js-apis-file-backup.md).
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).
2. Import **@ohos.file.backup**.
```js
import backup from '@ohos.file.backup';
```
## Obtaining the Capability File
Obtain the application capability file of the current system user. This file is 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.
Use **backup.getLocalCapabilities()** to obtain the capability file.
```js
import fs from '@ohos.file.fs';
async function getLocalCapabilities() {
try {
let fileData = await backup.getLocalCapabilities();
console.info('getLocalCapabilities success');
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
fs.copyFileSync(fileData.fd, fpath);
fs.closeSync(fileData.fd);
} catch (err) {
console.error('getLocalCapabilities failed with err: ' + err);
}
}
```
**Capability file example**
| Name | Type| Mandatory| Description |
| -------------- | -------- | ---- | ---------------------- |
| bundleInfos | Array | Yes | Application information. |
| allToBackup | Boolean | Yes | Whether to allow backup and restoration. |
| extensionName | String | Yes | Extension name of the application. |
| name | String | Yes | Bundle name of the application. |
| needToInstall | Boolean | Yes | Whether to install the application during data restoration.|
| spaceOccupied | Number | Yes | Space occupied by the application data.|
| versionCode | Number | Yes | Application version number. |
| versionName | String | Yes | Application version name. |
| deviceType | String | Yes | Type of the device. |
| systemFullName | String | Yes | Device version. |
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : false,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
## 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.
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.
You can save the file to a local directory as required.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionBackup instance for data backup.
let g_session;
function createSessionBackup() {
let sessionBackup = new backup.SessionBackup({
onFileReady: async (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
try {
let bundlePath = await globalThis.context.filesDir + '/' + file.bundleName;
if (!fs.accessSync(bundlePath)) {
fs.mkdirSync(bundlePath);
}
fs.copyFileSync(file.fd, bundlePath + `/${file.uri}`);
fs.closeSync(file.fd);
console.info('onFileReady success');
} catch (e) {
console.error('onFileReady failed with err: ' + e);
}
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.info('onBundleBegin err: ' + err);
} else {
console.info('onBundleBegin bundleName: ' + bundleName);
}
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.info('onBundleEnd err: ' + err);
} else {
console.info('onBundleEnd bundleName: ' + bundleName);
}
},
onAllBundlesEnd: (err) => {
if (err) {
console.info('onAllBundlesEnd err: ' + err);
} else {
console.info('onAllBundlesEnd');
}
},
onBackupServiceDied: () => {
console.info('onBackupServiceDied');
},
});
return sessionBackup;
}
async function sessionBackup ()
{
g_session = createSessionBackup();
// Select the application to be backed up based on the capability file obtained by backup.getLocalCapabilities().
// You can also back up data based on the application bundle name.
const backupApps = [
"com.example.hiworld",
]
await g_session.appendBundles(backupApps);
console.info('appendBundles success');
}
```
## Restoring Application Data
You can select the application data to be restored based on the application information provided by the capability file.
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.
When all the data of the application is ready, the service starts to restore the application data.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
bundleName: file.bundleName,
uri: file.uri
});
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
// Set bundlePath based on the actual situation.
let bundlePath;
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready.
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
return sessionRestore;
}
async function restore ()
{
g_session = createSessionRestore();
const backupApps = [
"com.example.hiworld",
]
// 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.
let fileData = await backup.getLocalCapabilities();
await g_session.appendBundles(fileData.fd, backupApps);
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.
// 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({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
}
```
## 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**.
> **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.
> - 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**.
**Example**
```ts
import fs from '@ohos.file.fs';
// Create a SessionRestore instance for data restoration.
let g_session;
async function publishFile(file)
{
await g_session.publishFile({
bundleName: file.bundleName,
uri: file.uri
});
}
function createSessionRestore() {
let sessionRestore = new backup.SessionRestore({
onFileReady: (err, file) => {
if (err) {
console.info('onFileReady err: ' + err);
}
let bundlePath;
if( file.uri == "/data/storage/el2/restore/bundle.hap" )
{
// Set the path of the application installation package based on actual situation.
} else {
// Set bundlePath based on the actual situation.
}
if (!fs.accessSync(bundlePath)) {
console.info('onFileReady bundlePath err : ' + bundlePath);
}
fs.copyFileSync(bundlePath, file.fd);
fs.closeSync(file.fd);
// After the data is transferred, notify the server that the file is ready.
publishFile(file);
console.info('onFileReady success');
},
onBundleBegin: (err, bundleName) => {
if (err) {
console.error('onBundleBegin failed with err: ' + err);
}
console.info('onBundleBegin success');
},
onBundleEnd: (err, bundleName) => {
if (err) {
console.error('onBundleEnd failed with err: ' + err);
}
console.info('onBundleEnd success');
},
onAllBundlesEnd: (err) => {
if (err) {
console.error('onAllBundlesEnd failed with err: ' + err);
}
console.info('onAllBundlesEnd success');
},
onBackupServiceDied: () => {
console.info('service died');
}
});
return sessionRestore;
}
async function restore ()
{
g_session = createSessionRestore();
const backupApps = [
"com.example.hiworld",
]
let fpath = await globalThis.context.filesDir + '/localCapabilities.json';
let file = fs.openSync(fpath, fileIO.OpenMode.CREATE | fileIO.OpenMode.READ_WRITE);
let content = "{\"bundleInfos\" :[{\"allToBackup\" : false,\"extensionName\" : \"\"," +
"\"name\" : \"cn.openharmony.inputmethodchoosedialog\",\"needToInstall\" : true,\"spaceOccupied\" : 0," +
"\"versionCode\" : 1000000,\"versionName\" : \"1.0.0\"}],\"deviceType\" : \"default\",\"systemFullName\" : \"OpenHarmony-4.0.6.2(Canary1)\"}";
fs.writeSync(file.fd, content);
fs.fsyncSync(file.fd);
await g_session.appendBundles(file.fd, backupApps);
console.info('appendBundles success');
// Obtain the file handle of the application to be installed.
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "/data/storage/el2/restore/bundle.hap"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "manage.json"
});
await g_session.getFileHandle({
bundleName: restoreApps[0],
uri: "1.tar"
});
console.info('getFileHandle success');
}
```
**Capability file example**
```json
{
"bundleInfos" :[{
"allToBackup" : true,
"extensionName" : "BackupExtensionAbility",
"name" : "com.example.hiworld",
"needToInstall" : true,
"spaceOccupied" : 0,
"versionCode" : 1000000,
"versionName" : "1.0.0"
}],
"deviceType" : "default",
"systemFullName" : "OpenHarmony-4.0.0.0"
}
```
......@@ -7,10 +7,11 @@ The operations for saving images, audio or video clips, and documents are simila
## Saving Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSaveOptions** instance.
......@@ -20,27 +21,43 @@ The operations for saving images, audio or video clips, and documents are simila
photoSaveOptions.newFileNames = ["PhotoViewPicker01.jpg"]; // (Optional) Set the names of the files to save.
```
3. Create a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) 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 a **photoViewPicker** instance and call [save()](../reference/apis/js-apis-file-picker.md#save) 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.
<br>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.
```ts
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.save(photoSaveOptions)
.then(async (photoSaveResult) => {
let uri = photoSaveResult[0];
// Perform operations on the files based on the file URIs obtained.
})
.catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
photoViewPicker.save(photoSaveOptions).then((photoSaveResult) => {
URI = photoSaveResult[0];
console.info('photoViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
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**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
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.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSaveOptions** instance.
......@@ -50,31 +67,43 @@ The operations for saving images, audio or video clips, and documents are simila
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // (Optional) Set the names of the documents 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.
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
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.
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.
```ts
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.save(documentSaveOptions)
.then(async (documentSaveResult) => {
let uri = documentSaveResult[0];
// For example, write data to the documents based on the obtained URIs.
})
.catch((err) => {
console.error(`Invoke documentPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
URI = documentSaveResult[0];
console.info('documentViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
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**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
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.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
## Saving Audio Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSaveOptions** instance.
......@@ -84,20 +113,33 @@ The operations for saving images, audio or video clips, and documents are simila
audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; // (Optional) Set the names of the files 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.
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
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.
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.
```ts
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.save(audioSaveOptions)
.then((audioSelectResult) => {
let uri = audioSelectResult[0];
// Perform operations on the audio files based on the file URIs.
})
.catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
audioViewPicker.save(audioSaveOptions).then((audioSelectResult) => {
URI = audioSelectResult[0];
console.info('audioViewPicker.save to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
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**.
```ts
let file = fs.openSync(URI, fs.OpenMode.READ_WRITE);
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.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
fs.closeSync(file);
```
# Selecting User Files
If your application needs to support share and saving of user files (such as images and videos) by users, you can use the [FilePicker](../reference/apis/js-apis-file-picker.md) prebuilt in OpenHarmony to implement selecting 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.
The **FilePicker** provides the following interfaces by file type:
......@@ -12,10 +12,11 @@ The **FilePicker** provides the following interfaces by file type:
## Selecting Images or Video Files
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **photoSelectOptions** instance.
......@@ -32,41 +33,44 @@ The **FilePicker** provides the following interfaces by file type:
photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images to select.
```
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files.
Use [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) to return a result set. Further operations on the selected files can be performed based on the file URIs in the result set.
4. Create a **photoPicker** instance and call [select()](../reference/apis/js-apis-file-picker.md#select) to open the **FilePicker** page for the user to select files. After the files are selected, [PhotoSelectResult](../reference/apis/js-apis-file-picker.md#photoselectresult) is returned.
<br>The permission on the URIs returned by **select()** is read-only. Further file operations can be performed based on the URIs in the **PhotoSelectResult**. 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
let uri = null;
const photoPicker = new picker.PhotoViewPicker();
photoPicker.select(photoSelectOptions).then((photoSelectResult) => {
uri = photoSelectResult.photoUris[0];
let URI = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
URI = photoSelectResult.photoUris[0];
console.info('photoViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke photoPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
5. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
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**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
6. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to write data to the file based on the FD, and then close the 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.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting Documents
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create a **documentSelectOptions** instance.
......@@ -75,23 +79,24 @@ The **FilePicker** provides the following interfaces by file type:
const documentSelectOptions = new picker.DocumentSelectOptions();
```
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents.
After the documents are selected successfully, a result set containing the file URIs is returned. Further operations can be performed on the documents based on the file URIs.
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).
3. Create a **documentViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-3) to open the **FilePicker** page for the user to select documents. After the documents are selected, a result set containing the file URIs is returned.
<br>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.
<br>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).
> **NOTE**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let URI = null;
const documentViewPicker = new picker.DocumentViewPicker(); // Create a documentViewPicker instance.
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
uri = documentSelectResult[0];
URI = documentSelectResult[0];
console.info('documentViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -109,7 +114,7 @@ The **FilePicker** provides the following interfaces by file type:
try {
let result = await context.startAbilityForResult(config, {windowMode: 1});
if (result.resultCode !== 0) {
console.error(`DocumentPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
console.error(`documentViewPicker.select failed, code is ${result.resultCode}, message is ${result.want.parameters.message}`);
return;
}
// Obtain the URI of the document.
......@@ -117,34 +122,34 @@ The **FilePicker** provides the following interfaces by file type:
// Obtain the name of the document.
let file_name_list = result.want.parameters.file_name_list;
} catch (err) {
console.error(`Invoke documentPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
```
4. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
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**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.readSync](../reference/apis/js-apis-file-fs.md#readsync) to read data from the file based on the FD, and then close the 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.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(4096);
let num = fs.readSync(file.fd, buf);
console.info('read data to file succeed and size is:' + num);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
## Selecting an Audio File
1. Import the **FilePicker** module.
1. Import the **picker** module and **fs** module.
```ts
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
```
2. Create an **audioSelectOptions** instance.
......@@ -153,37 +158,39 @@ The **FilePicker** provides the following interfaces by file type:
const audioSelectOptions = new picker.AudioSelectOptions();
```
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files.
After the files are selected successfully, a result set containing the URIs of the audio files selected is returned. Further operations can be performed on the documents based on the file URIs.
For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
3. Create an **audioViewPicker** instance, and call [**select()**](../reference/apis/js-apis-file-picker.md#select-6) to open the **FilePicker** page for the user to select audio files. After the files are selected, a result set containing the URIs of the audio files selected is returned.
<br>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.
<br>For example, use the [file management interface](../reference/apis/js-apis-file-fs.md) to obtain the file handle (FD) of the audio clip based on the URI, and then develop the audio playback function based on the media service. For details, see [Audio Playback Development](../media/audio-playback-overview.md).
> **NOTE**
>
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
let uri = null;
let URI = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
uri = audioSelectOptions[0];
URI = audioSelectOptions[0];
console.info('audioViewPicker.select to file succeed and URI is:' + URI);
}).catch((err) => {
console.error(`Invoke audioPicker.select failed, code is ${err.code}, message is ${err.message}`);
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
```
4. After the GUI is returned from FilePicker, use [**fs.openSync**](../reference/apis/js-apis-file-fs.md#fsopensync) to open the file based on the URI and obtain the FD.
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**.
```ts
let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
let file = fs.openSync(URI, fs.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
```
5. Use [fs.writeSync](../reference/apis/js-apis-file-fs.md#writesync) to write data to the file based on the FD, and then close the 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.
```ts
let writeLen = fs.writeSync(file.fd, 'hello, world');
console.info('write data to file succeed and size is:' + writeLen);
let buffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fs.closeSync(file);
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册