• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.multimedia.medialibrary (Media Library Management)
2
3> **NOTE**
4>
5> - The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
6> - This API is deprecated since API version 9 and will be retained until API version 13.
7> - Certain functionalities are changed as system APIs and can be used only by system applications. To use these functionalities, call [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md).
8> - The functionalities for selecting and storing media assets are still open to common applications. To use these functionalities, call [@ohos.file.picker](js-apis-file-picker.md).
9
10## Modules to Import
11```js
12import mediaLibrary from '@ohos.multimedia.mediaLibrary';
13```
14
15## mediaLibrary.getMediaLibrary<sup>8+</sup>
16
17getMediaLibrary(context: Context): MediaLibrary
18
19Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents.
20
21This API can be used only in the stage model.
22
23**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
24
25**Parameters**
26
27| Name | Type   | Mandatory| Description                      |
28| ------- | ------- | ---- | -------------------------- |
29| context | Context | Yes  | Context of the ability.|
30
31**Return value**
32
33| Type                           | Description   |
34| ----------------------------- | :---- |
35| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.|
36
37**Example (from API version 9)**
38
39```ts
40// Obtain a MediaLibrary instance. The instance obtained here is used in later.
41const context = getContext(this);
42let media = mediaLibrary.getMediaLibrary(context);
43```
44
45**Example (API version 8)**
46
47```js
48import featureAbility from '@ohos.ability.featureAbility';
49
50let context = featureAbility.getContext();
51let media = mediaLibrary.getMediaLibrary(context);
52```
53
54## mediaLibrary.getMediaLibrary
55
56getMediaLibrary(): MediaLibrary
57
58Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents.
59
60This API can be used only in the FA model.
61
62**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
63
64**Return value**
65
66| Type                         | Description      |
67| ----------------------------- | :--------- |
68| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.|
69
70**Example**
71
72```js
73let media = mediaLibrary.getMediaLibrary();
74```
75
76## MediaLibrary
77
78### getFileAssets<sup>7+</sup>
79
80getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void
81
82Obtains file assets (also called files). This API uses an asynchronous callback to return the result.
83
84**Required permissions**: ohos.permission.READ_MEDIA
85
86**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
87
88**Parameters**
89
90| Name  | Type                                               | Mandatory| Description                             |
91| -------- | --------------------------------------------------- | ---- | --------------------------------- |
92| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
93| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Asynchronous callback of **FetchFileResult**.|
94
95**Example**
96
97```js
98async function example() {
99    let fileKeyObj = mediaLibrary.FileKey;
100    let imageType = mediaLibrary.MediaType.IMAGE;
101    // Create options for fetching the files. The options are used to obtain files of the image type.
102    let imagesFetchOp = {
103        selections: fileKeyObj.MEDIA_TYPE + '= ?',
104        selectionArgs: [imageType.toString()],
105    };
106    // Obtain the files in asynchronous callback mode.
107    media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => {
108        // Check whether the result set of the obtained files is undefined. If yes, the API call fails.
109        if (fetchFileResult == undefined) {
110            console.error('get fetchFileResult failed with error: ' + error);
111            return;
112        }
113        // Obtain the total number of files in the result set.
114        const count = fetchFileResult.getCount();
115        // Check whether the number is less than 0. If yes, the API call fails.
116        if (count < 0) {
117            console.error('get count from fetchFileResult failed, count: ' + count);
118            return;
119        }
120        // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device.
121        if (count == 0) {
122            console.info('The count of fetchFileResult is zero');
123            return;
124        }
125        console.info('Get fetchFileResult successfully, count: ' + count);
126        // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject instead.
127        fetchFileResult.getFirstObject(async (error, fileAsset) => {
128            // Check whether the first file is undefined. If yes, the API call fails.
129            if (fileAsset == undefined) {
130                console.error('get first object failed with error: ' + error);
131                return;
132            }
133            console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
134            // Call getNextObject to obtain the next file until the last one.
135            for (let i = 1; i < count; i++) {
136                let fileAsset = await fetchFileResult.getNextObject();
137                console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
138            }
139            // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
140            fetchFileResult.close();
141        });
142    });
143}
144```
145
146### getFileAssets<sup>7+</sup>
147
148getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
149
150Obtains file assets. This API uses a promise to return the result.
151
152**Required permissions**: ohos.permission.READ_MEDIA
153
154**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
155
156**Parameters**
157
158| Name | Type                                    | Mandatory| Description        |
159| ------- | ---------------------------------------- | ---- | ------------ |
160| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the files.|
161
162**Return value**
163
164| Type                                | Description          |
165| ------------------------------------ | -------------- |
166| [FetchFileResult](#fetchfileresult7) | Result set of the file retrieval operation.|
167
168**Example**
169
170```js
171async function example() {
172    let fileKeyObj = mediaLibrary.FileKey;
173    let imageType = mediaLibrary.MediaType.IMAGE;
174    // Create options for fetching the files. The options are used to obtain files of the image type.
175    let imagesFetchOp = {
176        selections: fileKeyObj.MEDIA_TYPE + '= ?',
177        selectionArgs: [imageType.toString()],
178    };
179    // Obtain the files in promise mode.
180    media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => {
181        // Obtain the total number of files in the result set.
182        const count = fetchFileResult.getCount();
183        // Check whether the number is less than 0. If yes, the API call fails.
184        if (count < 0) {
185            console.error('get count from fetchFileResult failed, count: ' + count);
186            return;
187        }
188        // Check whether the number is 0. If yes, the API call is successful, but the result set is empty. Check whether the options for fetching the files are correctly set and whether the corresponding files exist on the device.
189        if (count == 0) {
190            console.info('The count of fetchFileResult is zero');
191            return;
192        }
193        console.info('Get fetchFileResult successfully, count: ' + count);
194        // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead.
195        fetchFileResult.getFirstObject().then(async (fileAsset) => {
196            console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
197            // Call getNextObject to obtain the next file until the last one.
198            for (let i = 1; i < count; i++) {
199                let fileAsset = await fetchFileResult.getNextObject();
200                console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
201            }
202            // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
203            fetchFileResult.close();
204        }).catch((error) => {
205            // Calling getFirstObject fails.
206            console.error('get first object failed with error: ' + error);
207        });
208    }).catch((error) => {
209        // Calling getFileAssets fails.
210        console.error('get file assets failed with error: ' + error);
211    });
212}
213```
214
215### on<sup>8+</sup>
216
217on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback: Callback&lt;void&gt;): void
218
219Subscribes to the media library changes. This API uses an asynchronous callback to return the result.
220
221**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
222
223**Parameters**
224
225| Name     | Type                  | Mandatory  | Description                                      |
226| -------- | -------------------- | ---- | ---------------------------------------- |
227| type     | 'deviceChange'&#124;<br>'albumChange'&#124;<br>'imageChange'&#124;<br>'audioChange'&#124;<br>'videoChange'&#124;<br>'fileChange'&#124;<br>'remoteFileChange'               | Yes   | Media type.<br>'deviceChange': registered device change<br>'albumChange': album change<br>'imageChange': image file change<br>'audioChange': audio file change<br>'videoChange': video file change<br>'fileChange': file change<br>'remoteFileChange': file change on the registered device|
228| callback | Callback&lt;void&gt; | Yes   | Void callback.                                   |
229
230**Example**
231
232```js
233media.on('imageChange', () => {
234    // image file had changed, do something
235})
236```
237### off<sup>8+</sup>
238
239off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback?: Callback&lt;void&gt;): void
240
241Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result.
242
243**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
244
245**Parameters**
246
247| Name     | Type                  | Mandatory  | Description                                      |
248| -------- | -------------------- | ---- | ---------------------------------------- |
249| type     | 'deviceChange'&#124;<br>'albumChange'&#124;<br>'imageChange'&#124;<br>'audioChange'&#124;<br>'videoChange'&#124;<br>'fileChange'&#124;<br>'remoteFileChange'               | Yes   | Media type.<br>'deviceChange': registered device change<br>'albumChange': album change<br>'imageChange': image file change<br>'audioChange': audio file change<br>'videoChange': video file change<br>'fileChange': file change<br>'remoteFileChange': file change on the registered device|
250| callback | Callback&lt;void&gt; | No   | Void callback.                                   |
251
252**Example**
253
254```js
255media.off('imageChange', () => {
256    // Stop listening successfully.
257})
258```
259
260### createAsset<sup>8+</sup>
261
262createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void
263
264Creates a media asset. This API uses an asynchronous callback to return the result.
265
266**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
267
268**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
269
270**Parameters**
271
272| Name      | Type                                   | Mandatory| Description                                                        |
273| ------------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
274| mediaType    | [MediaType](#mediatype8)                | Yes  | Media type.                                                    |
275| displayName  | string                                  | Yes  | Display file name.                                                  |
276| relativePath | string                                  | Yes  | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.|
277| callback     | AsyncCallback<[FileAsset](#fileasset7)> | Yes  | Asynchronous callback for **FileAsset**.                         |
278
279**Example**
280
281```js
282async function example() {
283    // Create an image file in callback mode.
284    let mediaType = mediaLibrary.MediaType.IMAGE;
285    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
286    const path = await media.getPublicDirectory(DIR_IMAGE);
287    media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => {
288        if (fileAsset != undefined) {
289            console.info('createAsset successfully, message');
290        } else {
291            console.error('createAsset failed with error: ' + error);
292        }
293    });
294}
295```
296
297### createAsset<sup>8+</sup>
298
299createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise&lt;FileAsset&gt;
300
301Creates a media asset. This API uses a promise to return the result.
302
303**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
304
305**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
306
307**Parameters**
308
309| Name      | Type                    | Mandatory| Description                                                        |
310| ------------ | ------------------------ | ---- | ------------------------------------------------------------ |
311| mediaType    | [MediaType](#mediatype8) | Yes  | Media type.                                                    |
312| displayName  | string                   | Yes  | Display file name.                                                  |
313| relativePath | string                   | Yes  | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.|
314
315**Return value**
316
317| Type                    | Description             |
318| ------------------------ | ----------------- |
319| [FileAsset](#fileasset7) | Media data (FileAsset).|
320
321**Example**
322
323```js
324async function example() {
325    // Create an image file in promise mode.
326    let mediaType = mediaLibrary.MediaType.IMAGE;
327    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
328    const path = await media.getPublicDirectory(DIR_IMAGE);
329    media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => {
330        console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset));
331    }).catch((error) => {
332        console.error('createAsset failed with error: ' + error);
333    });
334}
335```
336
337### deleteAsset<sup>8+</sup>
338
339deleteAsset(uri: string): Promise\<void>
340
341Deletes a file asset. This API uses a promise to return the result.
342
343**System API**: This is a system API.
344
345**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
346
347**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
348
349**Parameters**
350
351| Name     | Type                          | Mandatory  | Description             |
352| -------- | ---------------------------- | ---- | --------------- |
353| uri | string | Yes   | URI of the file asset to delete.|
354
355**Return value**
356| Type                 | Description                  |
357| ------------------- | -------------------- |
358| Promise&lt;void&gt; | Promise used to return the result.|
359
360**Example**
361
362```js
363async function example() {
364    let fileKeyObj = mediaLibrary.FileKey;
365    let fileType = mediaLibrary.MediaType.FILE;
366    let option = {
367        selections: fileKeyObj.MEDIA_TYPE + '= ?',
368        selectionArgs: [fileType.toString()],
369    };
370    const fetchFileResult = await media.getFileAssets(option);
371    let asset = await fetchFileResult.getFirstObject();
372    if (asset == undefined) {
373        console.error('asset not exist');
374        return;
375    }
376    media.deleteAsset(asset.uri).then(() => {
377        console.info('deleteAsset successfully');
378    }).catch((error) => {
379        console.error('deleteAsset failed with error: ' + error);
380    });
381    fetchFileResult.close();
382}
383```
384
385### deleteAsset<sup>8+</sup>
386deleteAsset(uri: string, callback: AsyncCallback\<void>): void
387
388Deletes a file asset. This API uses an asynchronous callback to return the result.
389
390**System API**: This is a system API.
391
392**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
393
394**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
395
396**Parameters**
397
398| Name     | Type                          | Mandatory  | Description             |
399| -------- | ---------------------------- | ---- | --------------- |
400| uri | string | Yes   | URI of the file asset to delete.|
401|callback |AsyncCallback\<void>| Yes |Callback used to return the result.|
402
403**Example**
404
405```js
406async function example() {
407    let fileKeyObj = mediaLibrary.FileKey;
408    let fileType = mediaLibrary.MediaType.FILE;
409    let option = {
410        selections: fileKeyObj.MEDIA_TYPE + '= ?',
411        selectionArgs: [fileType.toString()],
412    };
413    const fetchFileResult = await media.getFileAssets(option);
414    let asset = await fetchFileResult.getFirstObject();
415    if (asset == undefined) {
416        console.error('asset not exist');
417        return;
418    }
419    media.deleteAsset(asset.uri, (error) => {
420        if (error != undefined) {
421            console.error('deleteAsset failed with error: ' + error);
422        } else {
423            console.info('deleteAsset successfully');
424        }
425    });
426    fetchFileResult.close();
427}
428```
429
430### getPublicDirectory<sup>8+</sup>
431
432getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): void
433
434Obtains a public directory. This API uses an asynchronous callback to return the result.
435
436**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
437
438**Parameters**
439
440| Name  | Type                            | Mandatory| Description                     |
441| -------- | -------------------------------- | ---- | ------------------------- |
442| type     | [DirectoryType](#directorytype8) | Yes  | Type of the public directory.             |
443| callback | AsyncCallback&lt;string&gt;      | Yes  | Callback used to return the public directory.|
444
445**Example**
446
447```js
448let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
449media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => {
450    if (dicResult == 'Camera/') {
451        console.info('getPublicDirectory DIR_CAMERA successfully');
452    } else {
453        console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error);
454    }
455});
456```
457
458### getPublicDirectory<sup>8+</sup>
459
460getPublicDirectory(type: DirectoryType): Promise&lt;string&gt;
461
462Obtains a public directory. This API uses a promise to return the result.
463
464**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
465
466**Parameters**
467
468| Name| Type                            | Mandatory| Description        |
469| ------ | -------------------------------- | ---- | ------------ |
470| type   | [DirectoryType](#directorytype8) | Yes  | Type of the public directory.|
471
472**Return value**
473
474| Type            | Description            |
475| ---------------- | ---------------- |
476| Promise\<string> | Promise used to return the public directory.|
477
478**Example**
479
480```js
481async function example() {
482    let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
483    media.getPublicDirectory(DIR_CAMERA).then((dicResult) => {
484        if (dicResult == 'Camera/') {
485            console.info('getPublicDirectory DIR_CAMERA successfully');
486        } else {
487            console.error('getPublicDirectory DIR_CAMERA failed');
488        }
489    }).catch((error) => {
490        console.error('getPublicDirectory failed with error: ' + error);
491    });
492}
493```
494
495### getAlbums<sup>7+</sup>
496
497getAlbums(options: MediaFetchOptions, callback: AsyncCallback&lt;Array&lt;Album&gt;&gt;): void
498
499Obtains the albums. This API uses an asynchronous callback to return the result.
500
501**Required permissions**: ohos.permission.READ_MEDIA
502
503**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
504
505**Parameters**
506
507| Name  | Type                                        | Mandatory| Description                       |
508| -------- | -------------------------------------------- | ---- | --------------------------- |
509| options  | [MediaFetchOptions](#mediafetchoptions7)     | Yes  | Options for fetching the albums.               |
510| callback | AsyncCallback&lt;Array<[Album](#album7)>&gt; | Yes  | Callback used to return the albums.|
511
512**Example**
513
514```js
515async function example() {
516   // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
517  let AlbumNoArgsfetchOp = {
518    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
519    selectionArgs:['New Album 1'],
520  };
521  media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
522    if (albumList != undefined) {
523      console.info('getAlbums successfully: ' + JSON.stringify(albumList));
524    } else {
525      console.error('getAlbums failed with error: ' + error);
526    }
527  })
528}
529```
530
531### getAlbums<sup>7+</sup>
532
533getAlbums(options: MediaFetchOptions): Promise&lt;Array&lt;Album&gt;&gt;
534
535Obtains the albums. This API uses a promise to return the result.
536
537**Required permissions**: ohos.permission.READ_MEDIA
538
539**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
540
541**Parameters**
542
543| Name | Type                                    | Mandatory| Description        |
544| ------- | ---------------------------------------- | ---- | ------------ |
545| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the albums.|
546
547**Return value**
548
549| Type                            | Description         |
550| -------------------------------- | ------------- |
551| Promise<Array<[Album](#album7)>> | Promise used to return the albums.|
552
553**Example**
554
555```js
556async function example() {
557   // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
558  let AlbumNoArgsfetchOp = {
559    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
560    selectionArgs:['New Album 1'],
561  };
562  media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
563    console.info('getAlbums successfully: ' + JSON.stringify(albumList));
564  }).catch((error) => {
565    console.error('getAlbums failed with error: ' + error);
566  });
567}
568```
569
570### release<sup>8+</sup>
571
572release(callback: AsyncCallback&lt;void&gt;): void
573
574Releases this **MediaLibrary** instance.
575Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
576
577**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
578
579**Parameters**
580
581| Name     | Type                       | Mandatory  | Description        |
582| -------- | ------------------------- | ---- | ---------- |
583| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.|
584
585**Example**
586
587```js
588media.release(() => {
589    // do something
590});
591```
592
593### release<sup>8+</sup>
594
595release(): Promise&lt;void&gt;
596
597Releases this **MediaLibrary** instance.
598Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
599
600**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
601
602**Return value**
603
604| Type                 | Description                  |
605| ------------------- | -------------------- |
606| Promise&lt;void&gt; | Promise used to return the execution result.|
607
608**Example**
609
610```js
611media.release()
612```
613
614### storeMediaAsset
615
616storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;): void
617
618Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset.
619
620> **NOTE**
621>
622> This API is supported since API version 6 and can be used only by the FA model.
623
624**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
625
626**Parameters**
627
628| Name     | Type                                   | Mandatory  | Description                     |
629| -------- | ------------------------------------- | ---- | ----------------------- |
630| option   | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.                |
631| callback | AsyncCallback&lt;string&gt;           | Yes   | Callback used to return the URI that stores the media asset.|
632
633**Example**
634
635```js
636let option = {
637    src : '/data/storage/el2/base/haps/entry/image.png',
638    mimeType : 'image/*',
639    relativePath : 'Pictures/'
640};
641mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => {
642    if (error) {
643        console.error('storeMediaAsset failed with error: ' + error);
644        return;
645    }
646    console.info('Media resources stored. ');
647    // Obtain the URI that stores the media asset.
648});
649```
650
651
652### storeMediaAsset
653
654storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt;
655
656Stores a media asset. This API uses a promise to return the URI that stores the media asset.
657
658> **NOTE**
659>
660> This API is supported since API version 6 and can be used only by the FA model.
661
662**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
663
664**Parameters**
665
666| Name   | Type                                   | Mandatory  | Description     |
667| ------ | ------------------------------------- | ---- | ------- |
668| option | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.|
669
670**Return value**
671
672| Type                   | Description                          |
673| --------------------- | ---------------------------- |
674| Promise&lt;string&gt; | Promise used to return the URI that stores the media asset.|
675
676**Example**
677
678```js
679let option = {
680    src : '/data/storage/el2/base/haps/entry/image.png',
681    mimeType : 'image/*',
682    relativePath : 'Pictures/'
683};
684mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
685    console.info('Media resources stored.');
686    // Obtain the URI that stores the media asset.
687}).catch((error) => {
688    console.error('storeMediaAsset failed with error: ' + error);
689});
690```
691
692
693### startImagePreview
694
695startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCallback&lt;void&gt;): void
696
697Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result.
698
699> **NOTE**
700> This API is supported since API version 6 and can be used only by the FA model.
701> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\<Image>** component can be used to render and display local and online images.
702
703**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
704
705**Parameters**
706
707| Name     | Type                       | Mandatory  | Description                                      |
708| -------- | ------------------------- | ---- | ---------------------------------------- |
709| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
710| index    | number                    | Yes   | Index of the first image to preview.                              |
711| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the image preview result. If the preview fails, an error message is returned.                       |
712
713**Example**
714
715```js
716let images = [
717    'datashare:///media/xxxx/2',
718    'datashare:///media/xxxx/3'
719];
720/* Preview online images.
721let images = [
722    'https://media.xxxx.com/image1.jpg',
723    'https://media.xxxx.com/image2.jpg'
724];
725*/
726let index = 1;
727mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
728    if (error) {
729        console.error('startImagePreview failed with error: ' + error);
730        return;
731    }
732    console.info('Succeeded in previewing the images.');
733});
734```
735
736
737### startImagePreview
738
739startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void
740
741Starts image preview. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result.
742
743> **NOTE**
744> This API is supported since API version 6 and can be used only by the FA model.
745> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\<Image>** component can be used to render and display local and online images.
746
747**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
748
749**Parameters**
750
751| Name     | Type                       | Mandatory  | Description                                      |
752| -------- | ------------------------- | ---- | ---------------------------------------- |
753| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
754| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the image preview result. If the preview fails, an error message is returned.                       |
755
756**Example**
757
758```js
759let images = [
760    'datashare:///media/xxxx/2',
761    'datashare:///media/xxxx/3'
762];
763/* Preview online images.
764let images = [
765    'https://media.xxxx.com/image1.jpg',
766    'https://media.xxxx.com/image2.jpg'
767];
768*/
769mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
770    if (error) {
771        console.error('startImagePreview failed with error: ' + error);
772        return;
773    }
774    console.info('Succeeded in previewing the images.');
775});
776```
777
778
779### startImagePreview
780
781startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void&gt;
782
783Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses a promise to return the execution result.
784
785> **NOTE**
786> This API is supported since API version 6 and can be used only by the FA model.
787> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\<Image>** component can be used to render and display local and online images.
788
789**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
790
791**Parameters**
792
793| Name   | Type                 | Mandatory  | Description                                      |
794| ------ | ------------------- | ---- | ---------------------------------------- |
795| images | Array&lt;string&gt; | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
796| index  | number              | No   | Index of the first image to preview. If this parameter is not specified, the default value **0** is used.                     |
797
798**Return value**
799
800| Type                 | Description                             |
801| ------------------- | ------------------------------- |
802| Promise&lt;void&gt; | Promise used to return the image preview result. If the preview fails, an error message is returned.|
803
804**Example**
805
806```js
807let images = [
808    'datashare:///media/xxxx/2',
809    'datashare:///media/xxxx/3'
810];
811/* Preview online images.
812let images = [
813    'https://media.xxxx.com/image1.jpg',
814    'https://media.xxxx.com/image2.jpg'
815];
816*/
817let index = 1;
818mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
819    console.info('Succeeded in previewing the images.');
820}).catch((error) => {
821    console.error('startImagePreview failed with error: ' + error);
822});
823```
824
825
826### startMediaSelect
827
828startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
829
830Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets.
831
832> **NOTE**
833> This API is supported since API version 6 and can be used only by the FA model.
834> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
835
836**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
837
838**Parameters**
839
840| Name     | Type                                      | Mandatory  | Description                                  |
841| -------- | ---------------------------------------- | ---- | ------------------------------------ |
842| option   | [MediaSelectOption](#mediaselectoption)  | Yes   | Media selection option.                             |
843| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes   | Callback used to return the list of URIs (starting with **datashare://**) that store the selected media assets.|
844
845**Example**
846
847```js
848let option : mediaLibrary.MediaSelectOption = {
849    type : 'media',
850    count : 2
851};
852mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => {
853    if (error) {
854        console.error('startMediaSelect failed with error: ' + error);
855        return;
856    }
857    console.info('Media resources selected.');
858    // Obtain the media selection value.
859});
860```
861
862
863### startMediaSelect
864
865startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt;
866
867Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets.
868
869> **NOTE**
870> This API is supported since API version 6 and can be used only by the FA model.
871> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
872
873**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
874
875**Parameters**
876
877| Name   | Type                                     | Mandatory  | Description     |
878| ------ | --------------------------------------- | ---- | ------- |
879| option | [MediaSelectOption](#mediaselectoption) | Yes   | Media selection option.|
880
881**Return value**
882
883| Type                                | Description                                      |
884| ---------------------------------- | ---------------------------------------- |
885| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the list of URIs (starting with **datashare://**) that store the selected media assets.|
886
887**Example**
888
889```js
890let option : mediaLibrary.MediaSelectOption = {
891    type : 'media',
892    count : 2
893};
894mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
895    console.info('Media resources selected.');
896    // Obtain the media selection value.
897}).catch((error) => {
898    console.error('startMediaSelect failed with error: ' + error);
899});
900
901```
902### getActivePeers<sup>8+</sup>
903
904getActivePeers(): Promise\<Array\<PeerInfo>>;
905
906Obtains information about online peer devices. This API uses a promise to return the result.
907
908**System API**: This is a system API.
909
910**Required permissions**: ohos.permission.READ_MEDIA
911
912**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
913
914**Return value**
915
916| Type                 | Description                  |
917| ------------------- | -------------------- |
918|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
919
920**Example**
921
922```js
923async function example() {
924    media.getActivePeers().then((devicesInfo) => {
925        if (devicesInfo != undefined) {
926            console.info('get distributed info ' + JSON.stringify(devicesInfo));
927        } else {
928            console.info('get distributed info is undefined!');
929        }
930    }).catch((error) => {
931        console.error('get distributed info failed with error: ' + error);
932    });
933}
934```
935
936### getActivePeers<sup>8+</sup>
937
938getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
939
940Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
941
942**System API**: This is a system API.
943
944**Required permissions**: ohos.permission.READ_MEDIA
945
946**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
947
948**Return value**
949
950| Type                 | Description                  |
951| ------------------- | -------------------- |
952| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
953
954**Example**
955
956```js
957async function example() {
958    media.getActivePeers((error, devicesInfo) => {
959        if (devicesInfo != undefined) {
960            console.info('get distributed info ' + JSON.stringify(devicesInfo));
961        } else {
962            console.error('get distributed failed with error: ' + error);
963        }
964    });
965}
966```
967
968
969### getAllPeers<sup>8+</sup>
970
971getAllPeers(): Promise\<Array\<PeerInfo>>;
972
973Obtains information about all peer devices. This API uses a promise to return the result.
974
975**System API**: This is a system API.
976
977**Required permissions**: ohos.permission.READ_MEDIA
978
979**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
980
981**Return value**
982
983| Type                 | Description                  |
984| ------------------- | -------------------- |
985|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
986
987**Example**
988
989```js
990async function example() {
991    media.getAllPeers().then((devicesInfo) => {
992        if (devicesInfo != undefined) {
993            console.info('get distributed info ' + JSON.stringify(devicesInfo));
994        } else {
995            console.info('get distributed info is undefined!');
996        }
997    }).catch((error) => {
998        console.error('get distributed info failed with error: ' + error);
999    });
1000}
1001```
1002
1003### getAllPeers<sup>8+</sup>
1004
1005getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
1006
1007Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
1008
1009**System API**: This is a system API.
1010
1011**Required permissions**: ohos.permission.READ_MEDIA
1012
1013**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
1014
1015**Return value**
1016
1017| Type                 | Description                  |
1018| ------------------- | -------------------- |
1019| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
1020
1021**Example**
1022
1023```js
1024async function example() {
1025    media.getAllPeers((error, devicesInfo) => {
1026        if (devicesInfo != undefined) {
1027            console.info('get distributed info ' + JSON.stringify(devicesInfo));
1028        } else {
1029            console.error('get distributed failed with error: ' + error);
1030        }
1031    });
1032}
1033```
1034
1035## FileAsset<sup>7+</sup>
1036
1037Provides APIs for encapsulating file asset attributes.
1038
1039> **NOTE**
1040> 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices.
1041> 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module.
1042
1043### Attributes
1044
1045**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1046
1047| Name                     | Type                    | Readable| Writable| Description                                                  |
1048| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
1049| id                        | number                   | Yes  | No  | File asset ID.                                          |
1050| uri                       | string                   | Yes  | No  | File asset URI, for example, **datashare:///media/image/2**.        |
1051| mimeType                  | string                   | Yes  | No  | Extended file attributes.                                          |
1052| mediaType<sup>8+</sup>    | [MediaType](#mediatype8) | Yes  | No  | Media type.                                              |
1053| displayName               | string                   | Yes  | Yes  | Display file name, including the file name extension.                                |
1054| title                     | string                   | Yes  | Yes  | Title in the file. By default, it carries the file name without extension.                                              |
1055| relativePath<sup>8+</sup> | string                   | Yes  | Yes  | Relative public directory of the file.                                      |
1056| parent<sup>8+</sup>       | number                   | Yes  | No  | Parent directory ID.                                              |
1057| size                      | number                   | Yes  | No  | File size, in bytes.                                |
1058| dateAdded                 | number                   | Yes  | No  | Date when the file was added. The value is the number of seconds elapsed since the Epoch time.        |
1059| dateModified              | number                   | Yes  | No  | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.|
1060| dateTaken                 | number                   | Yes  | No  | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time.        |
1061| artist<sup>8+</sup>       | string                   | Yes  | No  | Artist of the file.                                                  |
1062| audioAlbum<sup>8+</sup>   | string                   | Yes  | No  | Audio album.                                                  |
1063| width                     | number                   | Yes  | No  | Image width, in pixels.                                |
1064| height                    | number                   | Yes  | No  | Image height, in pixels.                                |
1065| orientation               | number                   | Yes  | Yes  | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).|
1066| duration<sup>8+</sup>     | number                   | Yes  | No  | Duration, in ms.                                  |
1067| albumId                   | number                   | Yes  | No  | ID of the album to which the file belongs.                                  |
1068| albumUri<sup>8+</sup>     | string                   | Yes  | No  | URI of the album to which the file belongs.                                     |
1069| albumName                 | string                   | Yes  | No  | Name of the album to which the file belongs.                                    |
1070
1071
1072### isDirectory<sup>8+</sup>
1073
1074isDirectory(callback: AsyncCallback&lt;boolean&gt;): void
1075
1076Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result.
1077
1078**Required permissions**: ohos.permission.READ_MEDIA
1079
1080**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1081
1082**Parameters**
1083
1084| Name     | Type                          | Mandatory  | Description                 |
1085| -------- | ---------------------------- | ---- | ------------------- |
1086| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is a directory.|
1087
1088**Example**
1089
1090```js
1091async function example() {
1092    let fileKeyObj = mediaLibrary.FileKey;
1093    let imageType = mediaLibrary.MediaType.IMAGE;
1094    let getImageOp = {
1095        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1096        selectionArgs: [imageType.toString()],
1097        order: fileKeyObj.DATE_ADDED + ' DESC',
1098    };
1099    const fetchFileResult = await media.getFileAssets(getImageOp);
1100    const asset = await fetchFileResult.getFirstObject();
1101    asset.isDirectory((error, isDirectory) => {
1102        if (error) {
1103            console.error('isDirectory failed with error: ' + error);
1104        } else {
1105            console.info('isDirectory result:' + isDirectory);
1106        }
1107    });
1108    fetchFileResult.close();
1109}
1110```
1111
1112### isDirectory<sup>8+</sup>
1113
1114isDirectory():Promise&lt;boolean&gt;
1115
1116Checks whether this file asset is a directory. This API uses a promise to return the result.
1117
1118**Required permissions**: ohos.permission.READ_MEDIA
1119
1120**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1121
1122**Return value**
1123
1124| Type                    | Description                          |
1125| ---------------------- | ---------------------------- |
1126| Promise&lt;boolean&gt; | Promise used to return whether the file asset is a directory.|
1127
1128**Example**
1129
1130```js
1131async function example() {
1132    let fileKeyObj = mediaLibrary.FileKey;
1133    let imageType = mediaLibrary.MediaType.IMAGE;
1134    let getImageOp = {
1135        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1136        selectionArgs: [imageType.toString()],
1137        order: fileKeyObj.DATE_ADDED + ' DESC',
1138    };
1139    const fetchFileResult = await media.getFileAssets(getImageOp);
1140    const asset = await fetchFileResult.getFirstObject();
1141    asset.isDirectory().then((isDirectory) => {
1142        console.info('isDirectory result:' + isDirectory);
1143    }).catch((error) => {
1144        console.error('isDirectory failed with error: ' + error);
1145    });
1146    fetchFileResult.close();
1147}
1148```
1149
1150### commitModify<sup>8+</sup>
1151
1152commitModify(callback: AsyncCallback&lt;void&gt;): void
1153
1154Commits the modification in this file asset to the database. This API uses an asynchronous callback to return the result.
1155
1156**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1157
1158**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1159
1160**Parameters**
1161
1162| Name     | Type                       | Mandatory  | Description   |
1163| -------- | ------------------------- | ---- | ----- |
1164| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.|
1165
1166**Example**
1167
1168```js
1169async function example() {
1170    let fileKeyObj = mediaLibrary.FileKey;
1171    let imageType = mediaLibrary.MediaType.IMAGE;
1172    let getImageOp = {
1173        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1174        selectionArgs: [imageType.toString()],
1175        order: fileKeyObj.DATE_ADDED + ' DESC',
1176    };
1177    const fetchFileResult = await media.getFileAssets(getImageOp);
1178    const asset = await fetchFileResult.getFirstObject();
1179    asset.title = 'newtitle';
1180    asset.commitModify(() => {
1181        console.info('commitModify successfully');
1182    });
1183    fetchFileResult.close();
1184}
1185```
1186
1187### commitModify<sup>8+</sup>
1188
1189commitModify(): Promise&lt;void&gt;
1190
1191Commits the modification in this file asset to the database. This API uses a promise to return the result.
1192
1193**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1194
1195**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1196
1197**Return value**
1198
1199| Type                 | Description        |
1200| ------------------- | ---------- |
1201| Promise&lt;void&gt; | Void promise.|
1202
1203**Example**
1204
1205```js
1206async function example() {
1207    let fileKeyObj = mediaLibrary.FileKey;
1208    let imageType = mediaLibrary.MediaType.IMAGE;
1209    let getImageOp = {
1210        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1211        selectionArgs: [imageType.toString()],
1212        order: fileKeyObj.DATE_ADDED + ' DESC',
1213    };
1214    const fetchFileResult = await media.getFileAssets(getImageOp);
1215    const asset = await fetchFileResult.getFirstObject();
1216    asset.title = 'newtitle';
1217    await asset.commitModify();
1218    fetchFileResult.close();
1219}
1220```
1221
1222### open<sup>8+</sup>
1223
1224open(mode: string, callback: AsyncCallback&lt;number&gt;): void
1225
1226Opens this file asset. This API uses an asynchronous callback to return the result.
1227
1228**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
1229
1230**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
1231
1232**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1233
1234**Parameters**
1235
1236| Name     | Type                         | Mandatory  | Description                                 |
1237| -------- | --------------------------- | ---- | ----------------------------------- |
1238| mode     | string                      | Yes   | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).|
1239| callback | AsyncCallback&lt;number&gt; | Yes   | Callback used to return the file descriptor.                           |
1240
1241**Example**
1242
1243```js
1244async function example() {
1245    let mediaType = mediaLibrary.MediaType.IMAGE;
1246    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
1247    const path = await media.getPublicDirectory(DIR_IMAGE);
1248    const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
1249    asset.open('rw', (error, fd) => {
1250        if (fd > 0) {
1251            asset.close(fd);
1252        } else {
1253            console.error('File Open failed with error: ' + error);
1254        }
1255    });
1256}
1257```
1258
1259### open<sup>8+</sup>
1260
1261open(mode: string): Promise&lt;number&gt;
1262
1263Opens this file asset. This API uses a promise to return the result.
1264
1265**NOTE**: When a file is opened in 'w' mode, the returned FD cannot be read. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
1266
1267**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
1268
1269**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1270
1271**Parameters**
1272
1273| Name | Type    | Mandatory  | Description                                 |
1274| ---- | ------ | ---- | ----------------------------------- |
1275| mode | string | Yes   | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).|
1276
1277**Return value**
1278
1279| Type                   | Description           |
1280| --------------------- | ------------- |
1281| Promise&lt;number&gt; | Promise used to return the file descriptor.|
1282
1283**Example**
1284
1285```js
1286async function example() {
1287    let mediaType = mediaLibrary.MediaType.IMAGE;
1288    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
1289    const path = await media.getPublicDirectory(DIR_IMAGE);
1290    const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
1291    asset.open('rw').then((fd) => {
1292        console.info('File open fd: ' + fd);
1293    }).catch((error) => {
1294        console.error('File open failed with error: ' + error);
1295    });
1296}
1297```
1298
1299### close<sup>8+</sup>
1300
1301close(fd: number, callback: AsyncCallback&lt;void&gt;): void
1302
1303Closes this file asset. This API uses an asynchronous callback to return the result.
1304
1305**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
1306
1307**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1308
1309**Parameters**
1310
1311| Name     | Type                       | Mandatory  | Description   |
1312| -------- | ------------------------- | ---- | ----- |
1313| fd       | number                    | Yes   | File descriptor.|
1314| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.|
1315
1316**Example**
1317
1318```js
1319async function example() {
1320    let fileKeyObj = mediaLibrary.FileKey;
1321    let imageType = mediaLibrary.MediaType.IMAGE;
1322    let getImageOp = {
1323        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1324        selectionArgs: [imageType.toString()],
1325        order: fileKeyObj.DATE_ADDED + ' DESC',
1326    };
1327    const fetchFileResult = await media.getFileAssets(getImageOp);
1328    const asset = await fetchFileResult.getFirstObject();
1329    asset.open('rw').then((fd) => {
1330        console.info('File open fd: ' + fd);
1331        asset.close(fd, (error) => {
1332            if (error) {
1333                console.error('asset.close failed with error: ' + error);
1334            } else {
1335                console.info('asset.close successfully');
1336            }
1337        });
1338    }).catch((error) => {
1339        console.error('File open failed with error: ' + error);
1340    });
1341    fetchFileResult.close();
1342}
1343```
1344
1345### close<sup>8+</sup>
1346
1347close(fd: number): Promise&lt;void&gt;
1348
1349Closes this file asset. This API uses a promise to return the result.
1350
1351**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
1352
1353**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1354
1355**Parameters**
1356
1357| Name | Type    | Mandatory  | Description   |
1358| ---- | ------ | ---- | ----- |
1359| fd   | number | Yes   | File descriptor.|
1360
1361**Return value**
1362
1363| Type                 | Description        |
1364| ------------------- | ---------- |
1365| Promise&lt;void&gt; | Void promise.|
1366
1367**Example**
1368
1369```js
1370async function example() {
1371    let fileKeyObj = mediaLibrary.FileKey;
1372    let imageType = mediaLibrary.MediaType.IMAGE;
1373    let getImageOp = {
1374        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1375        selectionArgs: [imageType.toString()],
1376        order: fileKeyObj.DATE_ADDED + ' DESC',
1377    };
1378    const fetchFileResult = await media.getFileAssets(getImageOp);
1379    const asset = await fetchFileResult.getFirstObject();
1380    asset.open('rw').then((fd) => {
1381        console.info('File fd!' + fd);
1382        asset.close(fd).then(() => {
1383            console.info('asset.close successfully');
1384        }).catch((closeErr) => {
1385            console.error('asset.close fail, closeErr: ' + closeErr);
1386        });
1387    }).catch((error) => {
1388        console.error('open File failed with error: ' + error);
1389    });
1390    fetchFileResult.close();
1391}
1392```
1393
1394### getThumbnail<sup>8+</sup>
1395
1396getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void
1397
1398Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result.
1399
1400**Required permissions**: ohos.permission.READ_MEDIA
1401
1402**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1403
1404**Parameters**
1405
1406| Name     | Type                                 | Mandatory  | Description              |
1407| -------- | ----------------------------------- | ---- | ---------------- |
1408| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback used to return the pixel map of the thumbnail.|
1409
1410**Example**
1411
1412```js
1413async function example() {
1414    let fileKeyObj = mediaLibrary.FileKey;
1415    let imageType = mediaLibrary.MediaType.IMAGE;
1416    let getImageOp = {
1417        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1418        selectionArgs: [imageType.toString()],
1419        order: fileKeyObj.DATE_ADDED + ' DESC',
1420    };
1421    const fetchFileResult = await media.getFileAssets(getImageOp);
1422    const asset = await fetchFileResult.getFirstObject();
1423    asset.getThumbnail((error, pixelmap) => {
1424        if (error) {
1425            console.error('mediaLibrary getThumbnail failed with error: ' + error);
1426        } else {
1427            console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
1428        }
1429    });
1430    fetchFileResult.close();
1431}
1432```
1433
1434### getThumbnail<sup>8+</sup>
1435
1436getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void
1437
1438Obtains the thumbnail of this file asset, with the thumbnail size passed. This API uses an asynchronous callback to return the result.
1439
1440**Required permissions**: ohos.permission.READ_MEDIA
1441
1442**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1443
1444**Parameters**
1445
1446| Name     | Type                                 | Mandatory  | Description              |
1447| -------- | ----------------------------------- | ---- | ---------------- |
1448| size     | [Size](#size8)                      | Yes   | Size of the thumbnail.           |
1449| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback used to return the pixel map of the thumbnail.|
1450
1451**Example**
1452
1453```js
1454async function example() {
1455    let fileKeyObj = mediaLibrary.FileKey;
1456    let imageType = mediaLibrary.MediaType.IMAGE;
1457    let getImageOp = {
1458        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1459        selectionArgs: [imageType.toString()],
1460        order: fileKeyObj.DATE_ADDED + ' DESC',
1461    };
1462    let size = { width: 720, height: 720 };
1463    const fetchFileResult = await media.getFileAssets(getImageOp);
1464    const asset = await fetchFileResult.getFirstObject();
1465    asset.getThumbnail(size, (error, pixelmap) => {
1466        if (error) {
1467            console.error('mediaLibrary getThumbnail failed with error: ' + error);
1468        } else {
1469            console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
1470        }
1471    });
1472    fetchFileResult.close();
1473}
1474```
1475
1476### getThumbnail<sup>8+</sup>
1477
1478getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt;
1479
1480Obtains the thumbnail of this file asset, with the thumbnail size passed. This API uses a promise to return the result.
1481
1482**Required permissions**: ohos.permission.READ_MEDIA
1483
1484**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1485
1486**Parameters**
1487
1488| Name | Type            | Mandatory  | Description   |
1489| ---- | -------------- | ---- | ----- |
1490| size | [Size](#size8) | No   | Size of the thumbnail.|
1491
1492**Return value**
1493
1494| Type                           | Description                   |
1495| ----------------------------- | --------------------- |
1496| Promise&lt;image.PixelMap&gt; | Promise to return the pixel map of the thumbnail.|
1497
1498**Example**
1499
1500```js
1501async function example() {
1502    let fileKeyObj = mediaLibrary.FileKey;
1503    let imageType = mediaLibrary.MediaType.IMAGE;
1504    let getImageOp = {
1505        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1506        selectionArgs: [imageType.toString()],
1507        order: fileKeyObj.DATE_ADDED + ' DESC',
1508    };
1509    let size = { width: 720, height: 720 };
1510    const fetchFileResult = await media.getFileAssets(getImageOp);
1511    const asset = await fetchFileResult.getFirstObject();
1512    asset.getThumbnail(size).then((pixelmap) => {
1513        console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
1514    }).catch((error) => {
1515        console.error('mediaLibrary getThumbnail failed with error: ' + error);
1516    });
1517    fetchFileResult.close();
1518}
1519```
1520
1521### favorite<sup>8+</sup>
1522
1523favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void
1524
1525Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result.
1526
1527**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1528
1529**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1530
1531**Parameters**
1532
1533| Name       | Type                       | Mandatory  | Description                                |
1534| ---------- | ------------------------- | ---- | ---------------------------------- |
1535| isFavorite | boolean                   | Yes   | Whether to favorite or unfavorite the file. The value **true** means to favorite the file, and **false** means to unfavorite the file.|
1536| callback   | AsyncCallback&lt;void&gt; | Yes   | Void callback.                             |
1537
1538**Example**
1539
1540```js
1541async function example() {
1542    let fileKeyObj = mediaLibrary.FileKey;
1543    let imageType = mediaLibrary.MediaType.IMAGE;
1544    let getImageOp = {
1545        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1546        selectionArgs: [imageType.toString()],
1547        order: fileKeyObj.DATE_ADDED + ' DESC',
1548    };
1549    const fetchFileResult = await media.getFileAssets(getImageOp);
1550    const asset = await fetchFileResult.getFirstObject();
1551    asset.favorite(true,(error) => {
1552        if (error) {
1553            console.error('mediaLibrary favorite failed with error: ' + error);
1554        } else {
1555            console.info('mediaLibrary favorite Successful');
1556        }
1557    });
1558    fetchFileResult.close();
1559}
1560```
1561
1562### favorite<sup>8+</sup>
1563
1564favorite(isFavorite: boolean): Promise&lt;void&gt;
1565
1566Favorites or unfavorites this file asset. This API uses a promise to return the result.
1567
1568**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1569
1570**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1571
1572**Parameters**
1573
1574| Name       | Type     | Mandatory  | Description                                |
1575| ---------- | ------- | ---- | ---------------------------------- |
1576| isFavorite | boolean | Yes   | Whether to favorite or unfavorite the file. The value **true** means to favorite the file, and **false** means to unfavorite the file.|
1577
1578**Return value**
1579
1580| Type                 | Description        |
1581| ------------------- | ---------- |
1582| Promise&lt;void&gt; | Void promise.|
1583
1584**Example**
1585
1586```js
1587async function example() {
1588    let fileKeyObj = mediaLibrary.FileKey;
1589    let imageType = mediaLibrary.MediaType.IMAGE;
1590    let getImageOp = {
1591        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1592        selectionArgs: [imageType.toString()],
1593        order: fileKeyObj.DATE_ADDED + ' DESC',
1594    };
1595    const fetchFileResult = await media.getFileAssets(getImageOp);
1596    const asset = await fetchFileResult.getFirstObject();
1597    asset.favorite(true).then(() => {
1598        console.info('mediaLibrary favorite Successful');
1599    }).catch((error) => {
1600        console.error('mediaLibrary favorite failed with error: ' + error);
1601    });
1602    fetchFileResult.close();
1603}
1604```
1605
1606### isFavorite<sup>8+</sup>
1607
1608isFavorite(callback: AsyncCallback&lt;boolean&gt;): void
1609
1610Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result.
1611
1612**Required permissions**: ohos.permission.READ_MEDIA
1613
1614**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1615
1616**Parameters**
1617
1618| Name     | Type                          | Mandatory  | Description         |
1619| -------- | ---------------------------- | ---- | ----------- |
1620| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is favorited.|
1621
1622**Example**
1623
1624```js
1625async function example() {
1626    let fileKeyObj = mediaLibrary.FileKey;
1627    let imageType = mediaLibrary.MediaType.IMAGE;
1628    let getImageOp = {
1629        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1630        selectionArgs: [imageType.toString()],
1631        order: fileKeyObj.DATE_ADDED + ' DESC',
1632    };
1633    const fetchFileResult = await media.getFileAssets(getImageOp);
1634    const asset = await fetchFileResult.getFirstObject();
1635    asset.isFavorite((error, isFavorite) => {
1636        if (error) {
1637            console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
1638        } else {
1639            console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
1640        }
1641    });
1642    fetchFileResult.close();
1643}
1644```
1645
1646### isFavorite<sup>8+</sup>
1647
1648isFavorite():Promise&lt;boolean&gt;
1649
1650Checks whether this file asset is favorited. This API uses a promise to return the result.
1651
1652**Required permissions**: ohos.permission.READ_MEDIA
1653
1654**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1655
1656**Return value**
1657
1658| Type                    | Description                |
1659| ---------------------- | ------------------ |
1660| Promise&lt;boolean&gt; | Promise used to return whether the file asset is favorited.|
1661
1662**Example**
1663
1664```js
1665async function example() {
1666    let fileKeyObj = mediaLibrary.FileKey;
1667    let imageType = mediaLibrary.MediaType.IMAGE;
1668    let getImageOp = {
1669        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1670        selectionArgs: [imageType.toString()],
1671        order: fileKeyObj.DATE_ADDED + ' DESC',
1672    };
1673    const fetchFileResult = await media.getFileAssets(getImageOp);
1674    const asset = await fetchFileResult.getFirstObject();
1675    asset.isFavorite().then((isFavorite) => {
1676        console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
1677    }).catch((error) => {
1678        console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
1679    });
1680    fetchFileResult.close();
1681}
1682```
1683
1684### trash<sup>8+</sup>
1685
1686trash(isTrash: boolean, callback: AsyncCallback&lt;void&gt;): void
1687
1688Moves this file asset to the trash. This API uses an asynchronous callback to return the result.
1689
1690Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
1691
1692**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1693
1694**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1695
1696**Parameters**
1697
1698| Name     | Type                       | Mandatory  | Description       |
1699| -------- | ------------------------- | ---- | --------- |
1700| isTrash  | boolean                   | Yes   | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.|
1701| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.    |
1702
1703**Example**
1704
1705```js
1706async function example() {
1707    let fileKeyObj = mediaLibrary.FileKey;
1708    let imageType = mediaLibrary.MediaType.IMAGE;
1709    let getImageOp = {
1710        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1711        selectionArgs: [imageType.toString()],
1712        order: fileKeyObj.DATE_ADDED + ' DESC',
1713    };
1714    const fetchFileResult = await media.getFileAssets(getImageOp);
1715    const asset = await fetchFileResult.getFirstObject();
1716    asset.trash(true, (error) => {
1717        if (error) {
1718            console.error('mediaLibrary trash failed with error: ' + error);
1719        } else {
1720            console.info('mediaLibrary trash Successful');
1721        }
1722    });
1723    fetchFileResult.close();
1724}
1725```
1726
1727### trash<sup>8+</sup>
1728
1729trash(isTrash: boolean): Promise&lt;void&gt;
1730
1731Moves this file asset to the trash. This API uses a promise to return the result.
1732
1733Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
1734
1735**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
1736
1737**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1738
1739**Parameters**
1740
1741| Name    | Type     | Mandatory  | Description       |
1742| ------- | ------- | ---- | --------- |
1743| isTrash | boolean | Yes   | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.|
1744
1745**Return value**
1746
1747| Type                 | Description        |
1748| ------------------- | ---------- |
1749| Promise&lt;void&gt; | Void promise.|
1750
1751**Example**
1752
1753```js
1754async function example() {
1755    let fileKeyObj = mediaLibrary.FileKey;
1756    let imageType = mediaLibrary.MediaType.IMAGE;
1757    let getImageOp = {
1758        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1759        selectionArgs: [imageType.toString()],
1760        order: fileKeyObj.DATE_ADDED + ' DESC',
1761    };
1762    const fetchFileResult = await media.getFileAssets(getImageOp);
1763    const asset = await fetchFileResult.getFirstObject();
1764    asset.trash(true).then(() => {
1765        console.info('trash successfully');
1766    }).catch((error) => {
1767        console.error('trash failed with error: ' + error);
1768    });
1769    fetchFileResult.close();
1770}
1771```
1772
1773### isTrash<sup>8+</sup>
1774
1775isTrash(callback: AsyncCallback&lt;boolean&gt;): void
1776
1777Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result.
1778
1779**Required permissions**: ohos.permission.READ_MEDIA
1780
1781**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1782
1783**Parameters**
1784
1785| Name     | Type                          | Mandatory  | Description             |
1786| -------- | ---------------------------- | ---- | --------------- |
1787| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is in the trash. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|
1788
1789**Example**
1790
1791```js
1792async function example() {
1793    let fileKeyObj = mediaLibrary.FileKey;
1794    let imageType = mediaLibrary.MediaType.IMAGE;
1795    let getImageOp = {
1796        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1797        selectionArgs: [imageType.toString()],
1798        order: fileKeyObj.DATE_ADDED + ' DESC',
1799    };
1800    const fetchFileResult = await media.getFileAssets(getImageOp);
1801    const asset = await fetchFileResult.getFirstObject();
1802    asset.isTrash((error, isTrash) => {
1803        if (error) {
1804            console.error('Failed to get trash state failed with error: ' + error);
1805            return;
1806        }
1807        console.info('Get trash state successfully, isTrash result: ' + isTrash);
1808    });
1809    fetchFileResult.close();
1810}
1811```
1812
1813### isTrash<sup>8+</sup>
1814
1815isTrash():Promise&lt;boolean&gt;
1816
1817Checks whether this file asset is in the trash. This API uses a promise to return the result.
1818
1819**Required permissions**: ohos.permission.READ_MEDIA
1820
1821**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1822
1823**Return value**
1824
1825| Type                 | Description                  |
1826| ------------------- | -------------------- |
1827| Promise&lt;void&gt; | Promise used to return whether the file asset is in the trash. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|
1828
1829**Example**
1830
1831```js
1832async function example() {
1833    let fileKeyObj = mediaLibrary.FileKey;
1834    let imageType = mediaLibrary.MediaType.IMAGE;
1835    let getImageOp = {
1836        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1837        selectionArgs: [imageType.toString()],
1838        order: fileKeyObj.DATE_ADDED + ' DESC',
1839    };
1840    const fetchFileResult = await media.getFileAssets(getImageOp);
1841    const asset = await fetchFileResult.getFirstObject();
1842    asset.isTrash().then((isTrash) => {
1843        console.info('isTrash result: ' + isTrash);
1844    }).catch((error) => {
1845        console.error('isTrash failed with error: ' + error);
1846    });
1847    fetchFileResult.close();
1848}
1849```
1850
1851## FetchFileResult<sup>7+</sup>
1852
1853Implements the result set of the file retrieval operation.
1854
1855### getCount<sup>7+</sup>
1856
1857getCount(): number
1858
1859Obtains the total number of files in the result set.
1860
1861**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1862
1863**Return value**
1864
1865| Type    | Description      |
1866| ------ | -------- |
1867| number | Total number of files.|
1868
1869**Example**
1870
1871```js
1872async function example() {
1873    let fileKeyObj = mediaLibrary.FileKey;
1874    let fileType = mediaLibrary.MediaType.FILE;
1875    let getFileCountOneOp = {
1876        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1877        selectionArgs: [fileType.toString()],
1878        order: fileKeyObj.DATE_ADDED + ' DESC',
1879    };
1880    let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
1881    const fetchCount = fetchFileResult.getCount();
1882    console.info('fetchCount result: ' + fetchCount);
1883    fetchFileResult.close();
1884}
1885```
1886
1887### isAfterLast<sup>7+</sup>
1888
1889isAfterLast(): boolean
1890
1891Checks whether the cursor is in the last row of the result set.
1892
1893**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1894
1895**Return value**
1896
1897| Type     | Description                                |
1898| ------- | ---------------------------------- |
1899| boolean | Returns **true** if the cursor is in the last row of the result set; returns *false* otherwise.|
1900
1901**Example**
1902
1903```js
1904async function example() {
1905    let fileKeyObj = mediaLibrary.FileKey;
1906    let imageType = mediaLibrary.MediaType.IMAGE;
1907    let getImageOp = {
1908        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1909        selectionArgs: [imageType.toString()],
1910        order: fileKeyObj.DATE_ADDED + ' DESC',
1911    };
1912    let fetchFileResult = await media.getFileAssets(getImageOp);
1913    const fetchCount = fetchFileResult.getCount();
1914    console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount);
1915    let fileAsset = await fetchFileResult.getFirstObject();
1916    for (var i = 1; i < fetchCount; i++) {
1917        fileAsset = await fetchFileResult.getNextObject();
1918        if(i == fetchCount - 1) {
1919            var result = fetchFileResult.isAfterLast();
1920            console.info('mediaLibrary fileAsset isAfterLast result: ' + result);
1921            fetchFileResult.close();
1922        }
1923    }
1924}
1925```
1926
1927### close<sup>7+</sup>
1928
1929close(): void
1930
1931Releases and invalidates this **FetchFileResult** instance. Other APIs in this instance cannot be invoked after it is released.
1932
1933**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1934
1935**Example**
1936
1937```js
1938async function example() {
1939    let fileKeyObj = mediaLibrary.FileKey;
1940    let imageType = mediaLibrary.MediaType.IMAGE;
1941    let getImageOp = {
1942        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1943        selectionArgs: [imageType.toString()],
1944        order: fileKeyObj.DATE_ADDED + ' DESC',
1945    };
1946    let fetchFileResult = await media.getFileAssets(getImageOp);
1947    fetchFileResult.close();
1948}
1949```
1950
1951### getFirstObject<sup>7+</sup>
1952
1953getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void
1954
1955Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.
1956
1957**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1958
1959**Parameters**
1960
1961| Name  | Type                                         | Mandatory| Description                                       |
1962| -------- | --------------------------------------------- | ---- | ------------------------------------------- |
1963| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the first file asset.|
1964
1965**Example**
1966
1967```js
1968async function example() {
1969    let fileKeyObj = mediaLibrary.FileKey;
1970    let imageType = mediaLibrary.MediaType.IMAGE;
1971    let getImageOp = {
1972        selections: fileKeyObj.MEDIA_TYPE + '= ?',
1973        selectionArgs: [imageType.toString()],
1974        order: fileKeyObj.DATE_ADDED + ' DESC',
1975    };
1976    let fetchFileResult = await media.getFileAssets(getImageOp);
1977    fetchFileResult.getFirstObject((error, fileAsset) => {
1978        if (error) {
1979            console.error('fetchFileResult getFirstObject failed with error: ' + error);
1980            return;
1981        }
1982        console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName);
1983        fetchFileResult.close();
1984    })
1985}
1986```
1987
1988### getFirstObject<sup>7+</sup>
1989
1990getFirstObject(): Promise&lt;FileAsset&gt;
1991
1992Obtains the first file asset in the result set. This API uses a promise to return the result.
1993
1994**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
1995
1996**Return value**
1997
1998| Type                                   | Description                      |
1999| --------------------------------------- | -------------------------- |
2000| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the file asset.|
2001
2002**Example**
2003
2004```js
2005async function example() {
2006    let fileKeyObj = mediaLibrary.FileKey;
2007    let imageType = mediaLibrary.MediaType.IMAGE;
2008    let getImageOp = {
2009        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2010        selectionArgs: [imageType.toString()],
2011        order: fileKeyObj.DATE_ADDED + ' DESC',
2012    };
2013    let fetchFileResult = await media.getFileAssets(getImageOp);
2014    fetchFileResult.getFirstObject().then((fileAsset) => {
2015        console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName);
2016        fetchFileResult.close();
2017    }).catch((error) => {
2018        console.error('getFirstObject failed with error: ' + error);
2019    });
2020}
2021```
2022
2023### getNextObject<sup>7+</sup>
2024
2025getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
2026
2027Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
2028> **NOTE**
2029>
2030> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set.
2031
2032**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2033
2034**Parameters**
2035
2036| Name   | Type                                         | Mandatory| Description                                     |
2037| --------- | --------------------------------------------- | ---- | ----------------------------------------- |
2038| callback| AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the next file asset.|
2039
2040**Example**
2041
2042```js
2043async function example() {
2044    let fileKeyObj = mediaLibrary.FileKey;
2045    let imageType = mediaLibrary.MediaType.IMAGE;
2046    let getImageOp = {
2047        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2048        selectionArgs: [imageType.toString()],
2049        order: fileKeyObj.DATE_ADDED + ' DESC',
2050    };
2051    let fetchFileResult = await media.getFileAssets(getImageOp);
2052    let fileAsset = await fetchFileResult.getFirstObject();
2053    console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
2054    if (!fetchFileResult.isAfterLast()) {
2055        fetchFileResult.getNextObject((error, fileAsset) => {
2056            if (error) {
2057                console.error('fetchFileResult getNextObject failed with error: ' + error);
2058                return;
2059            }
2060            console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
2061            fetchFileResult.close();
2062        })
2063    }
2064}
2065
2066```
2067
2068### getNextObject<sup>7+</sup>
2069
2070getNextObject(): Promise&lt;FileAsset&gt;
2071
2072Obtains the next file asset in the result set. This API uses a promise to return the result.
2073> **NOTE**
2074>
2075> Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set.
2076
2077**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2078
2079**Return value**
2080
2081| Type                                   | Description             |
2082| --------------------------------------- | ----------------- |
2083| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
2084
2085**Example**
2086
2087```js
2088async function example() {
2089    let fileKeyObj = mediaLibrary.FileKey;
2090    let imageType = mediaLibrary.MediaType.IMAGE;
2091    let getImageOp = {
2092        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2093        selectionArgs: [imageType.toString()],
2094        order: fileKeyObj.DATE_ADDED + ' DESC',
2095    };
2096    let fetchFileResult = await media.getFileAssets(getImageOp);
2097    let fileAsset = await fetchFileResult.getFirstObject();
2098    console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
2099    if (!fetchFileResult.isAfterLast()) {
2100        fetchFileResult.getNextObject().then((fileAsset) => {
2101            console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
2102            fetchFileResult.close();
2103        }).catch((error) => {
2104            console.error('fetchFileResult getNextObject failed with error: ' + error);
2105        })
2106    }
2107}
2108```
2109
2110### getLastObject<sup>7+</sup>
2111
2112getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void
2113
2114Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.
2115
2116**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2117
2118**Parameters**
2119
2120| Name  | Type                                         | Mandatory| Description                       |
2121| -------- | --------------------------------------------- | ---- | --------------------------- |
2122| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the last file asset.|
2123
2124**Example**
2125
2126```js
2127async function example() {
2128    let fileKeyObj = mediaLibrary.FileKey;
2129    let imageType = mediaLibrary.MediaType.IMAGE;
2130    let getImageOp = {
2131        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2132        selectionArgs: [imageType.toString()],
2133        order: fileKeyObj.DATE_ADDED + ' DESC',
2134    };
2135    let fetchFileResult = await media.getFileAssets(getImageOp);
2136    fetchFileResult.getLastObject((error, fileAsset) => {
2137        if (error) {
2138            console.error('getLastObject failed with error: ' + error);
2139            return;
2140        }
2141        console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
2142        fetchFileResult.close();
2143    })
2144}
2145```
2146
2147### getLastObject<sup>7+</sup>
2148
2149getLastObject(): Promise&lt;FileAsset&gt;
2150
2151Obtains the last file asset in the result set. This API uses a promise to return the result.
2152
2153**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2154
2155**Return value**
2156
2157| Type                                   | Description             |
2158| --------------------------------------- | ----------------- |
2159| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
2160
2161**Example**
2162
2163```js
2164async function example() {
2165    let fileKeyObj = mediaLibrary.FileKey;
2166    let imageType = mediaLibrary.MediaType.IMAGE;
2167    let getImageOp = {
2168        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2169        selectionArgs: [imageType.toString()],
2170        order: fileKeyObj.DATE_ADDED + ' DESC',
2171    };
2172    let fetchFileResult = await media.getFileAssets(getImageOp);
2173    fetchFileResult.getLastObject().then((fileAsset) => {
2174        console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
2175        fetchFileResult.close();
2176    }).catch((error) => {
2177        console.error('getLastObject failed with error: ' + error);
2178    });
2179}
2180```
2181
2182### getPositionObject<sup>7+</sup>
2183
2184getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void
2185
2186Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.
2187
2188**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2189
2190**Parameters**
2191
2192| Name      | Type                                      | Mandatory  | Description                |
2193| -------- | ---------------------------------------- | ---- | ------------------ |
2194| index    | number                                   | Yes   | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set.    |
2195| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes   | Callback used to return the last file asset.|
2196
2197**Example**
2198
2199```js
2200async function example() {
2201    let fileKeyObj = mediaLibrary.FileKey;
2202    let imageType = mediaLibrary.MediaType.IMAGE;
2203    let getImageOp = {
2204        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2205        selectionArgs: [imageType.toString()],
2206        order: fileKeyObj.DATE_ADDED + ' DESC',
2207    };
2208    let fetchFileResult = await media.getFileAssets(getImageOp);
2209    fetchFileResult.getPositionObject(0, (error, fileAsset) => {
2210        if (error) {
2211            console.error('getPositionObject failed with error: ' + error);
2212            return;
2213        }
2214        console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
2215        fetchFileResult.close();
2216    })
2217}
2218```
2219
2220### getPositionObject<sup>7+</sup>
2221
2222getPositionObject(index: number): Promise&lt;FileAsset&gt;
2223
2224Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.
2225
2226**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2227
2228**Parameters**
2229
2230| Name   | Type    | Mandatory  | Description            |
2231| ----- | ------ | ---- | -------------- |
2232| index | number | Yes   | Index of the file to obtain. The value starts from 0 and must be smaller than the **count** value of the result set.|
2233
2234**Return value**
2235
2236| Type                                   | Description             |
2237| --------------------------------------- | ----------------- |
2238| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
2239
2240**Example**
2241
2242```js
2243async function example() {
2244    let fileKeyObj = mediaLibrary.FileKey;
2245    let imageType = mediaLibrary.MediaType.IMAGE;
2246    let getImageOp = {
2247        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2248        selectionArgs: [imageType.toString()],
2249        order: fileKeyObj.DATE_ADDED + ' DESC',
2250    };
2251    let fetchFileResult = await media.getFileAssets(getImageOp);
2252    fetchFileResult.getPositionObject(0).then((fileAsset) => {
2253        console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
2254        fetchFileResult.close();
2255    }).catch((error) => {
2256        console.error('getPositionObject failed with error: ' + error);
2257    });
2258}
2259```
2260
2261### getAllObject<sup>7+</sup>
2262
2263getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void
2264
2265Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result.
2266
2267**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2268
2269**Parameters**
2270
2271| Name      | Type                                      | Mandatory  | Description                  |
2272| -------- | ---------------------------------------- | ---- | -------------------- |
2273| callback | AsyncCallback&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | Yes   | Callback used to return the file assets.|
2274
2275**Example**
2276
2277```js
2278async function example() {
2279    let fileKeyObj = mediaLibrary.FileKey;
2280    let imageType = mediaLibrary.MediaType.IMAGE;
2281    let getImageOp = {
2282        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2283        selectionArgs: [imageType.toString()],
2284        order: fileKeyObj.DATE_ADDED + ' DESC',
2285    };
2286    let fetchFileResult = await media.getFileAssets(getImageOp);
2287    fetchFileResult.getAllObject((error, fileAssetList) => {
2288        if (error) {
2289           console.error('getAllObject failed with error: ' + error);
2290           return;
2291        }
2292        for (let i = 0; i < fetchFileResult.getCount(); i++) {
2293            console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
2294        }
2295        fetchFileResult.close();
2296    })
2297}
2298```
2299
2300### getAllObject<sup>7+</sup>
2301
2302getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt;
2303
2304Obtains all the file assets in the result set. This API uses a promise to return the result.
2305
2306**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2307
2308**Return value**
2309
2310| Type                                    | Description                 |
2311| ---------------------------------------- | --------------------- |
2312| Promise&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | Promise used to return the file assets.|
2313
2314**Example**
2315
2316```js
2317async function example() {
2318    let fileKeyObj = mediaLibrary.FileKey;
2319    let imageType = mediaLibrary.MediaType.IMAGE;
2320    let getImageOp = {
2321        selections: fileKeyObj.MEDIA_TYPE + '= ?',
2322        selectionArgs: [imageType.toString()],
2323        order: fileKeyObj.DATE_ADDED + ' DESC',
2324    };
2325    let fetchFileResult = await media.getFileAssets(getImageOp);
2326    fetchFileResult.getAllObject().then((fileAssetList) => {
2327        for (let i = 0; i < fetchFileResult.getCount(); i++) {
2328            console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
2329        }
2330        fetchFileResult.close();
2331    }).catch((error) => {
2332        console.error('getAllObject failed with error: ' + error);
2333    });
2334}
2335```
2336
2337## Album<sup>7+</sup>
2338
2339Provides APIs to implement a physical album.
2340
2341### Attributes
2342
2343**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2344
2345| Name          | Type   | Readable  | Writable  | Description     |
2346| ------------ | ------ | ---- | ---- | ------- |
2347| albumId | number | Yes   | No   | Album ID.   |
2348| albumName | string | Yes   | Yes   | Album name.   |
2349| albumUri<sup>8+</sup> | string | Yes   | No   | Album URI.  |
2350| dateModified | number | Yes   | No   | Date when the album was modified.   |
2351| count<sup>8+</sup> | number | Yes   | No   | Number of files in the album.|
2352| relativePath<sup>8+</sup> | string | Yes   | No   | Relative path of the album.   |
2353| coverUri<sup>8+</sup> | string | Yes   | No   | URI of the cover file of the album.|
2354
2355### commitModify<sup>8+</sup>
2356
2357commitModify(callback: AsyncCallback&lt;void&gt;): void
2358
2359Commits the modification in the album attributes to the database. This API uses an asynchronous callback to return the result.
2360
2361**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
2362
2363**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2364
2365**Parameters**
2366
2367| Name  | Type                     | Mandatory| Description      |
2368| -------- | ------------------------- | ---- | ---------- |
2369| callback | AsyncCallback&lt;void&gt; | Yes  | Void callback.|
2370
2371**Example**
2372
2373```js
2374async function example() {
2375  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
2376  let AlbumNoArgsfetchOp = {
2377    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
2378    selectionArgs:['New Album 1'],
2379  };
2380  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
2381  const album = albumList[0];
2382  album.albumName = 'hello';
2383  album.commitModify((error) => {
2384    if (error) {
2385      console.error('commitModify failed with error: ' + error);
2386      return;
2387    }
2388    console.info('commitModify successful.');
2389  })
2390}
2391```
2392
2393### commitModify<sup>8+</sup>
2394
2395commitModify(): Promise&lt;void&gt;
2396
2397Commits the modification in the album attributes to the database. This API uses a promise to return the result.
2398
2399**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
2400
2401**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2402
2403**Return value**
2404
2405| Type                 | Description          |
2406| ------------------- | ------------ |
2407| Promise&lt;void&gt; | Void promise.|
2408
2409**Example**
2410
2411```js
2412async function example() {
2413  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
2414  let AlbumNoArgsfetchOp = {
2415    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
2416    selectionArgs:['New Album 1'],
2417  };
2418  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
2419  const album = albumList[0];
2420  album.albumName = 'hello';
2421  album.commitModify().then(() => {
2422    console.info('commitModify successfully');
2423  }).catch((error) => {
2424    console.error('commitModify failed with error: ' + error);
2425  });
2426}
2427```
2428
2429### getFileAssets<sup>7+</sup>
2430
2431getFileAssets(callback: AsyncCallback&lt;FetchFileResult&gt;): void
2432
2433Obtains the file assets in this album. This API uses an asynchronous callback to return the result.
2434
2435**Required permissions**: ohos.permission.READ_MEDIA
2436
2437**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2438
2439**Parameters**
2440
2441| Name  | Type                                               | Mandatory| Description                               |
2442| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
2443| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback used to return the file assets.|
2444
2445**Example**
2446
2447```js
2448async function example() {
2449  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
2450  let AlbumNoArgsfetchOp = {
2451    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
2452    selectionArgs:['New Album 1'],
2453  };
2454  // Obtain the albums that meet the retrieval options and return the album list.
2455  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
2456  const album = albumList[0];
2457  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
2458  album.getFileAssets((error, fetchFileResult) => {
2459    if (error) {
2460      console.error('album getFileAssets failed with error: ' + error);
2461      return;
2462    }
2463    let count = fetchFileResult.getCount();
2464    console.info('album getFileAssets successfully, count: ' + count);
2465    fetchFileResult.close();
2466  });
2467}
2468```
2469
2470### getFileAssets<sup>7+</sup>
2471
2472getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void
2473
2474Obtains the file assets in this album. This API uses an asynchronous callback to return the result.
2475
2476**Required permissions**: ohos.permission.READ_MEDIA
2477
2478**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2479
2480**Parameters**
2481
2482| Name  | Type                                               | Mandatory| Description                               |
2483| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
2484| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
2485| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback used to return the file assets.|
2486
2487**Example**
2488
2489```js
2490async function example() {
2491  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
2492  let AlbumNoArgsfetchOp = {
2493    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
2494    selectionArgs:['New Album 1'],
2495  };
2496  let fileNoArgsfetchOp = {
2497    selections: '',
2498    selectionArgs: [],
2499  }
2500  // Obtain the albums that meet the retrieval options and return the album list.
2501  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
2502  const album = albumList[0];
2503  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
2504  album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
2505    if (error) {
2506      console.error('album getFileAssets failed with error: ' + error);
2507      return;
2508    }
2509    let count = fetchFileResult.getCount();
2510    console.info('album getFileAssets successfully, count: ' + count);
2511    fetchFileResult.close();
2512  });
2513}
2514```
2515
2516### getFileAssets<sup>7+</sup>
2517
2518 getFileAssets(options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
2519
2520Obtains the file assets in this album. This API uses a promise to return the result.
2521
2522**Required permissions**: ohos.permission.READ_MEDIA
2523
2524**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2525
2526**Parameters**
2527
2528| Name | Type                                    | Mandatory| Description          |
2529| ------- | ---------------------------------------- | ---- | -------------- |
2530| options | [MediaFetchOptions](#mediafetchoptions7) | No  | Options for fetching the files.|
2531
2532**Return value**
2533
2534| Type                                         | Description                     |
2535| --------------------------------------------- | ------------------------- |
2536| Promise<[FetchFileResult](#fetchfileresult7)> | Promise used to return the file assets.|
2537
2538**Example**
2539
2540```js
2541async function example() {
2542  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
2543  let AlbumNoArgsfetchOp = {
2544    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
2545    selectionArgs:['New Album 1'],
2546  };
2547  let fileNoArgsfetchOp = {
2548    selections: '',
2549    selectionArgs: [],
2550  };
2551  // Obtain the albums that meet the retrieval options and return the album list.
2552  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
2553  const album = albumList[0];
2554  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
2555  album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => {
2556    let count = fetchFileResult.getCount();
2557    console.info('album getFileAssets successfully, count: ' + count);
2558    fetchFileResult.close();
2559  }).catch((error) => {
2560    console.error('album getFileAssets failed with error: ' + error);
2561  });
2562}
2563```
2564
2565## PeerInfo<sup>8+</sup>
2566
2567Describes information about a registered device.
2568
2569**System API**: This is a system API.
2570
2571**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
2572
2573| Name      | Type                      | Readable| Writable| Description            |
2574| ---------- | -------------------------- | ---- | ---- | ---------------- |
2575| deviceName | string                     | Yes  | No  | Name of the registered device.  |
2576| networkId  | string                     | Yes  | No  | Network ID of the registered device.|
2577| deviceType | [DeviceType](#devicetype8) | Yes  | No  | Type of the registered device.        |
2578| isOnline   | boolean                    | Yes  | No  | Whether the registered device is online.        |
2579
2580
2581
2582## MediaType<sup>8+</sup>
2583
2584Enumerates media types.
2585
2586**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2587
2588| Name |  Value|  Description|
2589| ----- |  ---- | ---- |
2590| FILE  |  0 | File.|
2591| IMAGE |  1 | Image.|
2592| VIDEO |  2 | Video.|
2593| AUDIO |  3 | Audio.|
2594
2595## FileKey<sup>8+</sup>
2596
2597Enumerates key file information.
2598
2599> **NOTE**
2600> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
2601
2602**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2603
2604| Name         | Value             | Description                                                      |
2605| ------------- | ------------------- | ---------------------------------------------------------- |
2606| ID            | 'file_id'             | File ID.                                                  |
2607| RELATIVE_PATH | 'relative_path'       | Relative public directory of the file.                                          |
2608| DISPLAY_NAME  | 'display_name'        | Display file name.                                                  |
2609| PARENT        | 'parent'              | Parent directory ID.                                                  |
2610| MIME_TYPE     | 'mime_type'           | Extended file attributes, such as image/, video/, and file/*.                                            |
2611| MEDIA_TYPE    | 'media_type'          | Media type.                                                  |
2612| SIZE          | 'size'                | File size, in bytes.                                    |
2613| DATE_ADDED    | 'date_added'          | Date when the file was added. The value is the number of seconds elapsed since the Epoch time.            |
2614| DATE_MODIFIED | 'date_modified'       | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.|
2615| DATE_TAKEN    | 'date_taken'          | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time.            |
2616| TITLE         | 'title'               | Title in the file.                                                  |
2617| ARTIST        | 'artist'              | Artist of the file.                                                      |
2618| AUDIOALBUM    | 'audio_album'         | Audio album.                                                      |
2619| DURATION      | 'duration'            | Duration, in ms.                                      |
2620| WIDTH         | 'width'               | Image width, in pixels.                                    |
2621| HEIGHT        | 'height'              | Image height, in pixels.                                    |
2622| ORIENTATION   | 'orientation'         | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
2623| ALBUM_ID      | 'bucket_id'           | ID of the album to which the file belongs.                                      |
2624| ALBUM_NAME    | 'bucket_display_name' | Name of the album to which the file belongs.                                        |
2625
2626## DirectoryType<sup>8+</sup>
2627
2628Enumerates directory types.
2629
2630**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2631
2632| Name         | Value|  Description              |
2633| ------------- | --- | ------------------ |
2634| DIR_CAMERA    |  0 | Directory of camera files.|
2635| DIR_VIDEO     |  1 |  Directory of video files.      |
2636| DIR_IMAGE     |  2 | Directory of image files.      |
2637| DIR_AUDIO     |  3 | Directory of audio files.      |
2638| DIR_DOCUMENTS |  4 | Directory of documents.      |
2639| DIR_DOWNLOAD  |  5 |  Download directory.      |
2640
2641## DeviceType<sup>8+</sup>
2642
2643Enumerates device types.
2644
2645**System API**: This is a system API.
2646
2647**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
2648
2649| Name        |  Value| Description      |
2650| ------------ | --- | ---------- |
2651| TYPE_UNKNOWN |  0 | Unknown.|
2652| TYPE_LAPTOP  |  1 | Laptop.|
2653| TYPE_PHONE   |  2 | Phone.      |
2654| TYPE_TABLET  |  3 | Tablet.  |
2655| TYPE_WATCH   |  4 | Smart watch.  |
2656| TYPE_CAR     |  5 | Vehicle-mounted device.  |
2657| TYPE_TV      |  6 | TV.  |
2658
2659## MediaFetchOptions<sup>7+</sup>
2660
2661Describes options for fetching media files.
2662
2663**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2664
2665| Name                   | Type               | Readable| Writable| Description                                                        |
2666| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
2667| selections              | string              | Yes  | Yes  | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
2668| selectionArgs           | Array&lt;string&gt; | Yes  | Yes  | Value of the condition, which corresponds to the value of the condition column in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
2669| order                   | string              | Yes  | Yes  | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:<br>Ascending: order: mediaLibrary.FileKey.DATE_ADDED + ' ASC'<br>Descending: order: mediaLibrary.FileKey.DATE_ADDED + ' DESC'|
2670| uri<sup>8+</sup>        | string              | Yes  | Yes  | File URI.                                                     |
2671| networkId<sup>8+</sup>  | string              | Yes  | Yes  | Network ID of the registered device.                                              |
2672| extendArgs<sup>8+</sup> | string              | Yes  | Yes  | Extended parameters for fetching the files. Currently, no extended parameters are available.                        |
2673
2674## Size<sup>8+</sup>
2675
2676Describes the image size.
2677
2678**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2679
2680| Name    | Type    | Readable  | Writable  | Description      |
2681| ------ | ------ | ---- | ---- | -------- |
2682| width  | number | Yes   | Yes   | Image width, in pixels.|
2683| height | number | Yes   | Yes   | Image height, in pixels.|
2684
2685## MediaAssetOption
2686
2687Implements the media asset option.
2688
2689**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2690
2691
2692| Name        | Type  | Readable| Writable| Description                                                        |
2693| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
2694| src          | string | Yes  | Yes  | Application sandbox oath of the local file.                                      |
2695| mimeType     | string | Yes  | Yes  | Multipurpose Internet Mail Extensions (MIME) type of the media.<br>The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.|
2696| relativePath | string | Yes  | Yes  | Custom path for storing media assets, for example, 'Pictures/'. If this parameter is unspecified, media assets are stored in the default path.<br> Default path of images: 'Pictures/'<br> Default path of videos: 'Videos/'<br> Default path of audios: 'Audios/'<br> Default path of files: 'Documents/'|
2697
2698## MediaSelectOption
2699
2700Describes media selection option.
2701
2702**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
2703
2704| Name   | Type    | Readable| Writable| Description                  |
2705| ----- | ------ | ---- | ---- | -------------------- |
2706| type  | 'image' &#124; 'video' &#124; 'media' | Yes   | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
2707| count | number | Yes   | Yes | Maximum number of media assets that can be selected. The value starts from 1, which indicates that one media asset can be selected.           |
2708