@@ -36,7 +36,7 @@ You can use [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement ac
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).
Then, perform common file operations.
Then, perform file operations.
### Creating, Reading, and Writing a File
...
...
@@ -46,21 +46,29 @@ The following example demonstrates how to create a file, read data from it, and
// 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.
awaitg_session.getFileHandle({
lethandle:backup.FileMeta={
bundleName:restoreApps[0],
uri:"manage.json"
});
awaitg_session.getFileHandle({
bundleName:restoreApps[0],
uri:"1.tar"
});
}
awaitg_session.getFileHandle(handle);
handle.uri="1.tar";
awaitg_session.getFileHandle(handle);
console.info('getFileHandle success');
}
```
...
...
@@ -249,23 +265,30 @@ If the application has not been installed, you can install the application and t
@@ -8,46 +8,52 @@ For details about the APIs used to develop a file manager application, see [User
## How to Develop
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).
1. Apply for permissions required.
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**
>
> **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>
> **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
> - **ohos.permission.FILE_ACCESS_MANAGER** allows your application to use the user file access framework APIs.
>- **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** allows your application to obtain information about file management server applications supported by the system.
The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development.
3. Query device information.<br>
3. Query device information.
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, **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 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
// Start from the root directory.
letrootInfo=rootinfos[0];
letfileInfos=[];
letisDone=false;
letfilter={suffix:[".txt",".jpg",".xlsx"]};// Set filter criteria.
letrootInfo=rootInfos[0];
letfileInfos:Array<fileAccess.FileInfo>=[];
letisDone:boolean=false;
letfilter:Filter={suffix:[".txt",".jpg",".xlsx"]};// Set the filter.
try{
letfileIterator=rootInfo.listFile();// Traverse the root directory of rootinfos[0] and return an iterator object.
// let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return an iteration object.
if(!fileIterator){
console.error("listFile interface returns an undefined object");
return;
}
while(!isDone){
letresult=fileIterator.next();
...
...
@@ -92,35 +99,37 @@ For details about the APIs used to develop a file manager application, see [User
You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file (directory). The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis/js-apis-fileAccess.md).
```ts
...
...
@@ -128,18 +137,20 @@ For details about the APIs used to develop a file manager application, see [User
// Create a file.
// sourceUri is the URI in fileinfo of the Download directory.
// You need to use the obtained URI for development.
@@ -11,44 +11,48 @@ The **save()** method saves files in the file manager, not in **Gallery**.
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.
@@ -58,8 +62,8 @@ For example, select an image from **Gallery** and save it to the file manager.
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
leturi:string;
asyncphotoViewPickerSave(){
leturis:Array<string>;
asyncfunctionphotoViewPickerSave(){
try{
constphotoSaveOptions=newpicker.PhotoSaveOptions();// Create a photoSaveOptions instance.
photoSaveOptions.newFileNames=["PhotoViewPicker01.png"];// (Optional) Name of the file to be saved. The file name in the square brackets can be customized and must be unique. If the file name already exists on the device, change the file name. Otherwise, an error will be returned.
...
...
@@ -68,15 +72,16 @@ For example, select an image from **Gallery** and save it to the file manager.
@@ -86,14 +91,15 @@ For example, select an image from **Gallery** and save it to the file manager.
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.
@@ -105,6 +111,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create a **documentSaveOptions** instance.
...
...
@@ -112,6 +119,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
constdocumentSaveOptions=newpicker.DocumentSaveOptions();// Create a documentSaveOptions instance.
documentSaveOptions.newFileNames=["DocumentViewPicker01.txt"];// (Optional) Set the name of the document to save.
documentSaveOptions.fileSuffixChoices=['.png','.txt','.mp4'];// (Optional) Types 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 document. After the user selects the destination folder, the document is saved and the URI of the document saved is returned.
...
...
@@ -119,12 +127,12 @@ For example, select an image from **Gallery** and save it to the file manager.
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
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
console.info('documentViewPicker.save to file succeed and uris are:'+uris);
}).catch((err:BusinessError)=>{
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
```
...
...
@@ -151,6 +159,7 @@ For example, select an image from **Gallery** and save it to the file manager.
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create an **audioSaveOptions** instance.
...
...
@@ -160,17 +169,17 @@ For example, select an image from **Gallery** and save it to the file manager.
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 file. After the user selects the destination folder, the audio file is saved and the URI of the file saved is 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 document saved is returned.
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.
@@ -17,6 +17,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create a **photoSelectOptions** instance.
...
...
@@ -38,12 +39,12 @@ 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 **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.
documentSelectOptions.maxSelectNumber=5;// (Optional) Maximum number of documents to select.
documentSelectOptions.defaultFilePathUri="file://docs/storage/Users/currentUser/test";// (Optional) Path of the file or directory to select.
documentSelectOptions.fileSuffixFilters=['.png','.txt','.mp4'];// (Optional) File name extensions of the documents to select.
```
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.
...
...
@@ -85,17 +91,13 @@ The **FilePicker** provides the following interfaces by file type:
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**
>
> Currently, **DocumentSelectOptions** is not configurable. By default, all types of user files are selected.
```ts
leturi=null;
leturis:Array<string>;
constdocumentViewPicker=newpicker.DocumentViewPicker();// Create a documentViewPicker instance.
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
}
}
```
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**.
...
...
@@ -150,6 +155,7 @@ The **FilePicker** provides the following interfaces by file type:
```ts
importpickerfrom'@ohos.file.picker';
importfsfrom'@ohos.file.fs';
import{BusinessError}from'@ohos.base';
```
2. Create an **audioSelectOptions** instance.
...
...
@@ -169,12 +175,12 @@ The **FilePicker** provides the following interfaces by file type:
> Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
@@ -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:
**file**://<*bundleName*>/<*path*>
**file://**<bundleName>/<path>
-**file**: indicates a file URI.
...
...
@@ -43,6 +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.
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**
...
...
@@ -54,6 +55,8 @@ Before sharing application files, you need to [obtain the application file path]
console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`);
});
}
...
// ...
}
```
## 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**.
...
...
@@ -120,10 +123,12 @@ After obtaining the URI of the shared file from **want**, the application can ca
```ts
// xxx.ets
importfsfrom'@ohos.file.fs';
importWantfrom'@ohos.app.ability.Want';
import{BusinessError}from'@ohos.base';
functiongetShareFile(){
try{
letwant=...;// Obtain the want information sent from the application that shares the file.
letwant:Want=...;// Obtain the want sent from the application that shares the file.
// Obtain the uri field from the want information.
leturi=want.uri;
...
...
@@ -135,11 +140,13 @@ function getShareFile() {
// Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode.
letfile=fs.openSync(uri,fs.OpenMode.READ_WRITE);
console.info('open file successfully!');
}catch(error){
}catch(err){
leterror:BusinessError=errasBusinessError;
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
}
}catch(error){
console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`);
leterr:BusinessError=errorasBusinessError;
console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`);
Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery.
Saves one or more images or videos in a **photoPicker** page. This API uses a promise to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**.
Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves the file in the file manager, not in the Gallery.
Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. You can pass in **PhotoSaveOptions** to specify the file names of the images or videos to save. The **save()** API saves files in the file manager, not in **Gallery**.
Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves the file in the file manager, not in the Gallery.
Saves one or more images or videos in a **photoPicker** page. This API uses an asynchronous callback to return the result. The **save()** API saves files in the file manager, not in **Gallery**.
console.error('PhotoViewPicker failed with err: '+err);
}catch(error){
leterr:BusinessError=errorasBusinessError;
console.error('PhotoViewPicker failed with err: '+JSON.stringify(err));
}
}
```
## DocumentViewPicker
Provides APIs for selecting and saving non-media files, for example, documents in a variety of formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance.
Provides the **DocumentViewPicker** object for selecting and saving documents in different formats. Before using the APIs of **DocumentViewPicker**, you need to create a **DocumentViewPicker** instance.
| maxSelectNumber<sup>10+</sup> | number | No | Maximum number of files or directories that can be selected.<br>Value range: 1–500<br>Maximum value: **500** |
| defaultFilePathUri<sup>10+</sup> | string | No | Path of the file or directory to select.|
| fileSuffixFilters<sup>10+</sup> | Array<string> | No | File name extensions of the documents to select.|
## DocumentSaveOptions
Defines the options for saving documents.
...
...
@@ -753,7 +782,9 @@ Defines the options for saving documents.
| newFileNames? | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. |
| newFileNames | Array<string> | No | Names of the documents to save. If this parameter is not specified, the user needs to enter the document names. |
| defaultFilePathUri<sup>10+</sup> | string | No | Path of the file or directory to save.|
| fileSuffixChoices<sup>10+</sup> | Array<string> | No | File name extensions of the documents to save.|
## AudioSelectOptions
...
...
@@ -769,4 +800,4 @@ Defines the options for saving audio files.
| newFileNames? | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.|
| newFileNames | Array<string> | No | Name of the audio files to save. If this parameter is not specified, the user needs to enter the file names.|