• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Selecting User Files
2
3You can use [FilePicker](../reference/apis-core-file-kit/js-apis-file-picker.md) to implement the capabilities required for sharing user files and saving images and videos. When Picker is used to access a file, the related application will be started and guide the user to complete related operation on the UI. The caller does not require any permission. The permission on the file URI granted by Picker, however, is temporary. If required, you can persist the permission on the URI. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker).
4
5**FilePicker** provides the following types of Pickers by file type:
6
7- [PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated): used to select and save images and videos. However, the APIs of this Picker will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to select images and the [security component to save them](../media/medialibrary/photoAccessHelper-savebutton.md).
8
9- [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker): used to select and save documents. The **DocumentViewPicker** API triggers the **FilePicker** application. Documents are not distinguished by file name extensions. For example, the images and files downloaded from a browser are documents.
10
11- [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker): used to select and save audio clips. The **AudioViewPicker** API triggers the **FilePicker** application.
12
13## Selecting Images or Videos
14
15[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated) will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to select images.
16
17## Selecting Documents
18
191. Import modules.
20
21   ```ts
22   import  { picker } from '@kit.CoreFileKit';
23   import { fileIo as fs } from '@kit.CoreFileKit';
24   import { common } from '@kit.AbilityKit';
25   import { BusinessError } from '@kit.BasicServicesKit';
26   ```
27
282. Create a **DocumentSelectOptions** instance.
29
30   ```ts
31   const documentSelectOptions = new picker.DocumentSelectOptions();
32   // Set the maximum number of documents that can be selected. This parameter is optional.
33   documentSelectOptions.maxSelectNumber = 5;
34   // Specify the path of the files or folder to select. This parameter is optional.
35   documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test";
36   // (Optional. If this parameter is not transferred, all files are displayed by default.) Set the file name extension types ['File name extension description|File name extension type'] that can be selected. (Optional) Use a comma to separate multiple file name extensions, which cannot exceed 100. The wildcard ['All files (*.*)|.*'] can be used on 2-in-1 devices to display all files. Currently, mobile phones do not support this configuration.
37    documentSelectOptions.fileSuffixFilters = ['Image(.png, .jpg)|.png, .jpg', 'Document|.txt', 'Video|.mp4', '.pdf'];
38   // Whether to grant the permission for the specified files or folder. The value true means to grant the permission, the value false (default) means the opposite. If this parameter is true, defaultFilePathUri is mandatory and the file management authorization page is displayed. If this parameter is false, a common file management page is displayed. This parameter is optional and only 2-in-1 devices are supported.
39   documentSelectOptions.authMode = false;
40   // Whether to enable the batch authorization mode. The value true means to enable the batch authorization mode, and the value false (default) means the opposite. When multAuthMode is set to true, only the multiUriArray parameter takes effect. Only mobile phones are supported.
41   documentSelectOptions.multiAuthMode = false;
42   // Whether to pass the URIs for batch authorization. (Only files are supported and folders are not supported.) This parameter does not take effect when multAuthMode is set to false. Only mobile phones are supported.
43   documentSelectOptions.multiUriArray = ["file://docs/storage/Users/currentUser/test", "file://docs/storage/Users/currentUser/2test"];
44   // Whether to enable the aggregation view mode to launch the file management application. The value DEFAULT means that this parameter does not take effect and the aggregation view mode is disabled. Values other than DEFAULT means that other parameters do not take effect. Only mobile phones are supported.
45   documentSelectOptions.mergeMode = picker.MergeTypeMode.DEFAULT;
46   ```
47
483. Create a [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) instance, and call [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) to start the FilePicker application page for the user to select documents.
49
50   ```ts
51   let uris: Array<string> = [];
52   let context = getContext (this) as common.Context; // Ensure that getContext (this) returns UIAbilityContext.
53   // Create a DocumentViewPicker instance.
54   const documentViewPicker = new picker.DocumentViewPicker(context);
55   documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {
56     // After the user selects documents, a result set containing the document URIs is returned.
57     uris = documentSelectResult;
58     console.info('documentViewPicker.select to file succeed and uris are:' + uris);
59   }).catch((err: BusinessError) => {
60     console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
61   })
62   ```
63
64  > **NOTE**
65  >
66  > - The permission for the URI returned by [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) of Picker is a temporary read-only permission. The temporary permission will be invalidated once the application exits.
67  >
68  > - You can persist the temporary permission for a URI. This operation is available only for 2-in-1 devices. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker).
69  >
70  > - Further operations can be performed on the documents based on the file URIs returned in the result set. You are advised to define a global variable to save the URI.
71  >
72  > - If metadata needs to be obtained, you can use the [@ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) and [@ohos.file.fileuri](../reference/apis-core-file-kit/js-apis-file-fileuri.md) APIs to obtain document attribute information, such as the document name, size, access time, modification time, and path, based on the URI.
73
744. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open a document based on the URI. The file descriptor (FD) is obtained.
75
76   ```ts
77   let uri: string = '';
78   // Note that the mode parameter of fs.openSync() is fs.OpenMode.READ_ONLY.
79   let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
80   console.info('file fd: ' + file.fd);
81   ```
82
835. Call [fs.readSync](../reference/apis-core-file-kit/js-apis-file-fs.md#readsync) to read data from the document based on the FD.
84
85   ```ts
86   let buffer = new ArrayBuffer(4096);
87   let readLen = fs.readSync(file.fd, buffer);
88   console.info('readSync data to file succeed and buffer size is:' + readLen);
89   // Close the FD after the data is read.
90   fs.closeSync(file);
91   ```
92
93## Selecting Audio Clips
94
951. Import modules.
96
97   ```ts
98   import  { picker } from '@kit.CoreFileKit';
99   import { fileIo as fs } from '@kit.CoreFileKit';
100   import { BusinessError } from '@kit.BasicServicesKit';
101   import { common } from '@kit.AbilityKit';
102   ```
103
1042. Create an **AudioSelectOptions** instance.
105
106   > **NOTE**
107   >
108   > Currently, **AudioSelectOptions** is not configurable. By default, all types of user files are selected.
109
110   ```ts
111   const audioSelectOptions = new picker.AudioSelectOptions();
112   ```
113
1143. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance, and call [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-5) to start the FilePicker application page for the user to select audio clips.
115
116   ```ts
117   let uris: string = '';
118   // Ensure that getContext(this) returns UIAbilityContext.
119   let context = getContext(this) as common.Context;
120   const audioViewPicker = new picker.AudioViewPicker(context);
121   audioViewPicker.select(audioSelectOptions).then((audioSelectResult: Array<string>) => {
122     // After the user selects audio clips, a result set containing the URIs of the audio clips selected is returned.
123     uris = audioSelectResult[0];
124     console.info('audioViewPicker.select to file succeed and uri is:' + uris);
125   }).catch((err: BusinessError) => {
126     console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
127   })
128   ```
129
130  > **NOTE**
131  >
132  > - The permission for the URI returned by [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) of Picker is a temporary read-only permission. The temporary permission will be invalidated once the application exits.
133  >
134  > - You can persist the temporary permission for a URI. This operation is available only for 2-in-1 devices. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker).
135  >
136  > - You can read file data based on the URI. You are advised to define a global variable to save the URI. For example, you can use the [@ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) API to obtain the FD of the audio clip based on the URI, and then develop the audio playback application with the media service. For details, see [Audio Playback Development](../media/audio/audio-playback-overview.md).
137
1384. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open an audio clip based on the URI. The FD is obtained.
139
140   ```ts
141   let uri: string = '';
142   // Note that the mode parameter of fs.openSync() is fs.OpenMode.READ_ONLY.
143   let file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
144   console.info('file fd: ' + file.fd);
145   ```
146
1475. Call [fs.readSync](../reference/apis-core-file-kit/js-apis-file-fs.md#readsync) to read data from the audio clip based on the FD.
148
149   ```ts
150   let buffer = new ArrayBuffer(4096);
151   let readLen = fs.readSync(file.fd, buffer);
152   console.info('readSync data to file succeed and buffer size is:' + readLen);
153   // Close the FD after the data is read.
154   fs.closeSync(file);
155   ```
156
157<!--RP1--><!--RP1End-->
158