js-apis-medialibrary.md 102.7 KB
Newer Older
G
gloria 已提交
1
# @ohos.multimedia.medialibrary (Media Library Management)
W
wusongqing 已提交
2

W
wusongqing 已提交
3
> **NOTE**
G
Gloria 已提交
4
>
G
Gloria 已提交
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.
A
Annie_wang 已提交
6 7 8
> - The APIs of this module are deprecated since API version 9 and will be retained until API version 13.
> - Some APIs are changed as system APIs and can be used only by system applications. Use  [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md) instead.
> - The APIs for selecting and storing media assets are still open to common applications. Use [@ohos.file.picker](js-apis-file-picker.md) instead.
W
wusongqing 已提交
9 10

## Modules to Import
A
Annie_wang 已提交
11

12
```js
W
wusongqing 已提交
13
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
W
wusongqing 已提交
14 15
```

W
wusongqing 已提交
16
## mediaLibrary.getMediaLibrary<sup>8+</sup>
W
wusongqing 已提交
17 18 19

getMediaLibrary(context: Context): MediaLibrary

W
wusongqing 已提交
20
Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents.
W
wusongqing 已提交
21

22 23
This API can be used only in the stage model.

W
wusongqing 已提交
24 25 26 27
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
28 29 30
| Name | Type   | Mandatory| Description                      |
| ------- | ------- | ---- | -------------------------- |
| context | Context | Yes  | Context of the ability.|
W
wusongqing 已提交
31 32 33

**Return value**

W
wusongqing 已提交
34 35
| Type                           | Description   |
| ----------------------------- | :---- |
W
wusongqing 已提交
36 37
| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.|

W
wusongqing 已提交
38 39
**Example (from API version 9)**

40
```ts
G
Gloria 已提交
41
// Obtain a MediaLibrary instance. The instance obtained here is used in later.
42 43
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
W
wusongqing 已提交
44 45 46
```

**Example (API version 8)**
W
wusongqing 已提交
47

48
```js
W
wusongqing 已提交
49 50
import featureAbility from '@ohos.ability.featureAbility';

51 52
let context = featureAbility.getContext();
let media = mediaLibrary.getMediaLibrary(context);
W
wusongqing 已提交
53
```
54

W
wusongqing 已提交
55 56 57 58 59 60
## mediaLibrary.getMediaLibrary

getMediaLibrary(): MediaLibrary

Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents.

61 62
This API can be used only in the FA model.

W
wusongqing 已提交
63 64 65 66 67 68 69 70 71 72 73
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

| Type                         | Description      |
| ----------------------------- | :--------- |
| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.|

**Example**

```js
74
let media = mediaLibrary.getMediaLibrary();
W
wusongqing 已提交
75 76
```

W
wusongqing 已提交
77 78
## MediaLibrary

W
wusongqing 已提交
79
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
80 81 82 83 84

getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void 

Obtains file assets (also called files). This API uses an asynchronous callback to return the result.

A
Annie_wang 已提交
85 86 87
> **NOTE**
> From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).

W
wusongqing 已提交
88 89 90 91 92 93
**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
94 95 96
| Name  | Type                                               | Mandatory| Description                             |
| -------- | --------------------------------------------------- | ---- | --------------------------------- |
| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
A
Annie_wang 已提交
97
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback invoked to return the file retrieval result set.|
W
wusongqing 已提交
98 99 100

**Example**

101
```js
G
Gloria 已提交
102
async function example() {
A
Annie_wang 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  // Create options for fetching the files of the image type.
  let imagesFetchOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
  };
  // Obtain the files in asynchronous callback mode.
  media.getFileAssets(imagesFetchOp, async (error, fetchFileResult) => {
    // Check whether the result set of the obtained files is undefined. If yes, the API call fails.
    if (fetchFileResult == undefined) {
      console.error('get fetchFileResult failed with error: ' + error);
      return;
    }
    // Obtain the total number of files in the result set.
    const count = fetchFileResult.getCount();
    // Check whether the number is less than 0. If yes, the API call fails.
    if (count < 0) {
      console.error('get count from fetchFileResult failed, count: ' + count);
      return;
    }
    // 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.
    if (count == 0) {
      console.info('The count of fetchFileResult is zero');
      return;
    }
    console.info('Get fetchFileResult successfully, count: ' + count);
    // Obtain the first file in the result set in asynchronous callback mode. If there are a large number of files, use getAllObject() instead.
    fetchFileResult.getFirstObject(async (error, fileAsset) => {
      // Check whether the first file is undefined. If yes, the API call fails.
      if (fileAsset == undefined) {
        console.error('get first object failed with error: ' + error);
        return;
      }
      console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
      // Call getNextObject to obtain the next file until the last one.
      for (let i = 1; i < count; i++) {
        let fileAsset = await fetchFileResult.getNextObject();
        console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
      }
      // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
      fetchFileResult.close();
145
    });
A
Annie_wang 已提交
146
  });
G
Gloria 已提交
147
}
W
wusongqing 已提交
148
```
G
Gloria 已提交
149

W
wusongqing 已提交
150
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
151 152 153 154 155

getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;

Obtains file assets. This API uses a promise to return the result.

A
Annie_wang 已提交
156 157 158
> **NOTE**
> From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).

W
wusongqing 已提交
159 160 161 162 163 164
**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
165 166 167
| Name | Type                                    | Mandatory| Description        |
| ------- | ---------------------------------------- | ---- | ------------ |
| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the files.|
W
wusongqing 已提交
168 169 170

**Return value**

W
wusongqing 已提交
171 172
| Type                                | Description          |
| ------------------------------------ | -------------- |
A
Annie_wang 已提交
173
| Promise&lt;[FetchFileResult](#fetchfileresult7)&gt; | Promise used to return the file retrieval result set.|
W
wusongqing 已提交
174 175 176

**Example**

177
```js
G
Gloria 已提交
178
async function example() {
A
Annie_wang 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  // Create options for fetching the files of the image type.
  let imagesFetchOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
  };
  // Obtain the files in promise mode.
  media.getFileAssets(imagesFetchOp).then(async (fetchFileResult) => {
    // Obtain the total number of files in the result set.
    const count = fetchFileResult.getCount();
    // Check whether the number is less than 0. If yes, the API call fails.
    if (count < 0) {
      console.error('get count from fetchFileResult failed, count: ' + count);
      return;
    }
    // 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.
    if (count == 0) {
      console.info('The count of fetchFileResult is zero');
      return;
    }
    console.info('Get fetchFileResult successfully, count: ' + count);
    // Obtain the first file in the result set in promise mode. If there are a large number of files, use getAllObject instead.
    fetchFileResult.getFirstObject().then(async (fileAsset) => {
      console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
      // Call getNextObject to obtain the next file until the last one.
      for (let i = 1; i < count; i++) {
        let fileAsset = await fetchFileResult.getNextObject();
        console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
      }
      // Release the FetchFileResult instance and invalidate it. Other APIs can no longer be called.
      fetchFileResult.close();
G
Gloria 已提交
211
    }).catch((error) => {
A
Annie_wang 已提交
212 213
      // Calling getFirstObject fails.
      console.error('get first object failed with error: ' + error);
214
    });
A
Annie_wang 已提交
215 216 217 218
  }).catch((error) => {
    // Calling getFileAssets fails.
    console.error('get file assets failed with error: ' + error);
  });
G
Gloria 已提交
219
}
W
wusongqing 已提交
220 221 222 223
```

### on<sup>8+</sup>

G
gloria 已提交
224
on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback: Callback&lt;void&gt;): void
W
wusongqing 已提交
225

A
Annie_wang 已提交
226
Subscribes to the media library changes. This API uses a callback to return the result.
W
wusongqing 已提交
227 228 229 230 231

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
232 233
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
A
Annie_wang 已提交
234 235
| type     | 'deviceChange'&#124;<br>'albumChange'&#124;<br>'imageChange'&#124;<br>'audioChange'&#124;<br>'videoChange'&#124;<br>'fileChange'&#124;<br>'remoteFileChange'               | Yes   | Type of the event to subscribe to.<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|
| callback | Callback&lt;void&gt; | Yes   | Callback that returns no value.                                   |
W
wusongqing 已提交
236 237 238

**Example**

239
```js
W
wusongqing 已提交
240
media.on('imageChange', () => {
A
Annie_wang 已提交
241 242
  // image file had changed, do something.
});
W
wusongqing 已提交
243
```
A
Annie_wang 已提交
244

W
wusongqing 已提交
245 246
### off<sup>8+</sup>

G
gloria 已提交
247
off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback?: Callback&lt;void&gt;): void
W
wusongqing 已提交
248

A
Annie_wang 已提交
249
Unsubscribes from the media library changes. This API uses a callback to return the result.
W
wusongqing 已提交
250 251 252 253 254

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
255 256
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
A
Annie_wang 已提交
257 258
| type     | 'deviceChange'&#124;<br>'albumChange'&#124;<br>'imageChange'&#124;<br>'audioChange'&#124;<br>'videoChange'&#124;<br>'fileChange'&#124;<br>'remoteFileChange'               | Yes   | Type of the event to unsubscribe from.<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|
| callback | Callback&lt;void&gt; | No   | Callback that returns no value.                                   |
W
wusongqing 已提交
259 260 261

**Example**

262
```js
W
wusongqing 已提交
263
media.off('imageChange', () => {
A
Annie_wang 已提交
264 265
  // stop listening successfully.
});
W
wusongqing 已提交
266 267
```

268
### createAsset<sup>8+</sup>
W
wusongqing 已提交
269 270 271 272 273

createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void

Creates a media asset. This API uses an asynchronous callback to return the result.

A
Annie_wang 已提交
274 275 276
> **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).

W
wusongqing 已提交
277 278 279 280 281 282
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
283 284 285
| Name      | Type                                   | Mandatory| Description                                                        |
| ------------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
| mediaType    | [MediaType](#mediatype8)                | Yes  | Media type.                                                    |
A
Annie_wang 已提交
286 287 288
| displayName  | string                                  | Yes  | File name to display.                                                  |
| relativePath | string                                  | Yes  | Path of the file, which can be obtained by using [getPublicDirectory](#getpublicdirectory8).|
| callback     | AsyncCallback<[FileAsset](#fileasset7)> | Yes  | Callback invoked to return the **FileAsset** instance created.                         |
W
wusongqing 已提交
289 290 291

**Example**

292
```js
W
wusongqing 已提交
293
async function example() {
A
Annie_wang 已提交
294 295 296 297 298 299 300 301 302 303 304
  // Create an image file in callback mode.
  let mediaType = mediaLibrary.MediaType.IMAGE;
  let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
  const path = await media.getPublicDirectory(DIR_IMAGE);
  media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => {
    if (fileAsset != undefined) {
      console.info('createAsset successfully, message');
    } else {
      console.error('createAsset failed with error: ' + error);
    }
  });
W
wusongqing 已提交
305 306 307 308 309 310 311 312 313
}
```

### createAsset<sup>8+</sup>

createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise&lt;FileAsset&gt;

Creates a media asset. This API uses a promise to return the result.

A
Annie_wang 已提交
314 315 316
> **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).

W
wusongqing 已提交
317 318 319 320 321 322
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
323 324 325
| Name      | Type                    | Mandatory| Description                                                        |
| ------------ | ------------------------ | ---- | ------------------------------------------------------------ |
| mediaType    | [MediaType](#mediatype8) | Yes  | Media type.                                                    |
A
Annie_wang 已提交
326 327
| displayName  | string                   | Yes  | File name to display.                                                  |
| relativePath | string                   | Yes  | Relative path of the file, which can be obtained by [getPublicDirectory](#getpublicdirectory8).|
W
wusongqing 已提交
328 329 330

**Return value**

W
wusongqing 已提交
331 332
| Type                    | Description             |
| ------------------------ | ----------------- |
A
Annie_wang 已提交
333
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the **FileAsset** instance created.|
W
wusongqing 已提交
334 335 336

**Example**

337
```js
338
async function example() {
A
Annie_wang 已提交
339 340 341 342 343 344 345 346 347
  // Create an image file in promise mode.
  let mediaType = mediaLibrary.MediaType.IMAGE;
  let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
  const path = await media.getPublicDirectory(DIR_IMAGE);
  media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => {
    console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset));
  }).catch((error) => {
    console.error('createAsset failed with error: ' + error);
  });
348
}
W
wusongqing 已提交
349 350
```

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
### deleteAsset<sup>8+</sup>

deleteAsset(uri: string): Promise\<void>

Deletes a file asset. This API uses a promise to return the result.

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

| Name     | Type                          | Mandatory  | Description             |
| -------- | ---------------------------- | ---- | --------------- |
| uri | string | Yes   | URI of the file asset to delete.|

**Return value**
A
Annie_wang 已提交
370

371 372 373 374 375 376 377 378
| Type                 | Description                  |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Example**

```js
async function example() {
A
Annie_wang 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.FILE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
  };
  const fetchFileResult = await media.getFileAssets(option);
  let asset = await fetchFileResult.getFirstObject();
  if (asset == undefined) {
    console.error('asset not exist');
    return;
  }
  media.deleteAsset(asset.uri).then(() => {
    console.info('deleteAsset successfully');
  }).catch((error) => {
    console.error('deleteAsset failed with error: ' + error);
  });
  fetchFileResult.close();
397 398 399 400
}
```

### deleteAsset<sup>8+</sup>
A
Annie_wang 已提交
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
deleteAsset(uri: string, callback: AsyncCallback\<void>): void

Deletes a file asset. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

| Name     | Type                          | Mandatory  | Description             |
| -------- | ---------------------------- | ---- | --------------- |
| uri | string | Yes   | URI of the file asset to delete.|
A
Annie_wang 已提交
417
|callback |AsyncCallback\<void>| Yes |Callback that returns no value.|
418 419 420 421 422

**Example**

```js
async function example() {
A
Annie_wang 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.FILE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
  };
  const fetchFileResult = await media.getFileAssets(option);
  let asset = await fetchFileResult.getFirstObject();
  if (asset == undefined) {
    console.error('asset not exist');
    return;
  }
  media.deleteAsset(asset.uri, (error) => {
    if (error != undefined) {
      console.error('deleteAsset failed with error: ' + error);
    } else {
      console.info('deleteAsset successfully');
440
    }
A
Annie_wang 已提交
441 442
  });
  fetchFileResult.close();
443 444 445
}
```

W
wusongqing 已提交
446 447 448 449
### getPublicDirectory<sup>8+</sup>

getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): void

A
Annie_wang 已提交
450
Obtains a user directory. This API uses an asynchronous callback to return the result.
W
wusongqing 已提交
451 452 453 454 455

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
456 457
| Name  | Type                            | Mandatory| Description                     |
| -------- | -------------------------------- | ---- | ------------------------- |
A
Annie_wang 已提交
458 459
| type     | [DirectoryType](#directorytype8) | Yes  | Type of the user directory.             |
| callback | AsyncCallback&lt;string&gt;      | Yes  | Callback invoked to return the user directory obtained.|
W
wusongqing 已提交
460 461 462

**Example**

463
```js
W
wusongqing 已提交
464
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
G
Gloria 已提交
465
media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => {
A
Annie_wang 已提交
466 467 468 469 470
  if (dicResult == 'Camera/') {
    console.info('getPublicDirectory DIR_CAMERA successfully');
  } else {
    console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error);
  }
W
wusongqing 已提交
471 472 473 474 475 476 477
});
```

### getPublicDirectory<sup>8+</sup>

getPublicDirectory(type: DirectoryType): Promise&lt;string&gt;

A
Annie_wang 已提交
478
Obtains a user directory. This API uses a promise to return the result.
W
wusongqing 已提交
479 480 481 482 483

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
484 485
| Name| Type                            | Mandatory| Description        |
| ------ | -------------------------------- | ---- | ------------ |
A
Annie_wang 已提交
486
| type   | [DirectoryType](#directorytype8) | Yes  | Type of the user directory.|
W
wusongqing 已提交
487 488 489

**Return value**

W
wusongqing 已提交
490 491
| Type            | Description            |
| ---------------- | ---------------- |
A
Annie_wang 已提交
492
| Promise\<string> | Promise used to return the user directory obtained.|
W
wusongqing 已提交
493 494 495

**Example**

496
```js
W
wusongqing 已提交
497
async function example() {
A
Annie_wang 已提交
498 499 500 501 502 503 504 505 506 507
  let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
  media.getPublicDirectory(DIR_CAMERA).then((dicResult) => {
    if (dicResult == 'Camera/') {
      console.info('getPublicDirectory DIR_CAMERA successfully');
    } else {
      console.error('getPublicDirectory DIR_CAMERA failed');
    }
  }).catch((error) => {
    console.error('getPublicDirectory failed with error: ' + error);
  });
W
wusongqing 已提交
508 509 510
}
```

W
wusongqing 已提交
511
### getAlbums<sup>7+</sup>
W
wusongqing 已提交
512

G
Gloria 已提交
513
getAlbums(options: MediaFetchOptions, callback: AsyncCallback&lt;Array&lt;Album&gt;&gt;): void
W
wusongqing 已提交
514

A
Annie_wang 已提交
515 516 517 518
Obtains albums. This API uses an asynchronous callback to return the result.

> **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
W
wusongqing 已提交
519 520 521 522 523 524 525

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
526 527
| Name  | Type                                        | Mandatory| Description                       |
| -------- | -------------------------------------------- | ---- | --------------------------- |
A
Annie_wang 已提交
528 529
| options  | [MediaFetchOptions](#mediafetchoptions7)     | Yes  | Options for fetching albums.               |
| callback | AsyncCallback&lt;Array<[Album](#album7)>&gt; | Yes  | Callback invoked to return the albums.|
W
wusongqing 已提交
530 531 532

**Example**

533
```js
G
Gloria 已提交
534
async function example() {
535 536
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
A
Annie_wang 已提交
537
    selectionArgs: ['Camera'],
538 539 540 541 542 543 544
  };
  media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
    if (albumList != undefined) {
      console.info('getAlbums successfully: ' + JSON.stringify(albumList));
    } else {
      console.error('getAlbums failed with error: ' + error);
    }
A
Annie_wang 已提交
545
  });
G
Gloria 已提交
546
}
W
wusongqing 已提交
547 548
```

W
wusongqing 已提交
549
### getAlbums<sup>7+</sup>
W
wusongqing 已提交
550

G
Gloria 已提交
551
getAlbums(options: MediaFetchOptions): Promise&lt;Array&lt;Album&gt;&gt;
W
wusongqing 已提交
552

A
Annie_wang 已提交
553 554 555 556
Obtains albums. This API uses a promise to return the result.

> **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
W
wusongqing 已提交
557 558 559 560 561 562 563

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
564 565 566
| Name | Type                                    | Mandatory| Description        |
| ------- | ---------------------------------------- | ---- | ------------ |
| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the albums.|
W
wusongqing 已提交
567 568 569

**Return value**

W
wusongqing 已提交
570 571 572
| Type                            | Description         |
| -------------------------------- | ------------- |
| Promise<Array<[Album](#album7)>> | Promise used to return the albums.|
W
wusongqing 已提交
573 574 575

**Example**

576
```js
G
Gloria 已提交
577
async function example() {
578 579
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
A
Annie_wang 已提交
580
    selectionArgs: ['Camera'],
581 582 583 584 585 586
  };
  media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
    console.info('getAlbums successfully: ' + JSON.stringify(albumList));
  }).catch((error) => {
    console.error('getAlbums failed with error: ' + error);
  });
G
Gloria 已提交
587
}
W
wusongqing 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600
```

### release<sup>8+</sup>

release(callback: AsyncCallback&lt;void&gt;): void

Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
601 602
| Name     | Type                       | Mandatory  | Description        |
| -------- | ------------------------- | ---- | ---------- |
G
Gloria 已提交
603
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.|
W
wusongqing 已提交
604 605 606

**Example**

607
```js
G
Gloria 已提交
608
media.release(() => {
A
Annie_wang 已提交
609
  // do something.
W
wusongqing 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623
});
```

### release<sup>8+</sup>

release(): Promise&lt;void&gt;

Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
624 625
| Type                 | Description                  |
| ------------------- | -------------------- |
A
Annie_wang 已提交
626
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
627 628 629

**Example**

630
```js
A
Annie_wang 已提交
631
media.release();
W
wusongqing 已提交
632 633
```

G
Gloria 已提交
634
### storeMediaAsset
W
wusongqing 已提交
635 636 637

storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;): void

A
Annie_wang 已提交
638
Stores a media asset. This API uses an asynchronous callback to return the URI of the media asset.
W
wusongqing 已提交
639

A
Annie_wang 已提交
640
> **NOTE**<br>This API is supported since API version 6 and can be used only in the FA model.
W
wusongqing 已提交
641 642 643 644 645

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
646 647 648
| Name     | Type                                   | Mandatory  | Description                     |
| -------- | ------------------------------------- | ---- | ----------------------- |
| option   | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.                |
A
Annie_wang 已提交
649
| callback | AsyncCallback&lt;string&gt;           | Yes   | Callback invoked to return the URI of the media resource saved.|
W
wusongqing 已提交
650 651 652

**Example**

653
```js
W
wusongqing 已提交
654
let option = {
A
Annie_wang 已提交
655 656 657
  src : '/data/storage/el2/base/haps/entry/image.png',
  mimeType : 'image/*',
  relativePath : 'Pictures/'
W
wusongqing 已提交
658
};
G
Gloria 已提交
659
mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => {
A
Annie_wang 已提交
660 661 662 663 664 665
  if (error) {
    console.error('storeMediaAsset failed with error: ' + error);
    return;
  }
  console.info('Media resources stored. ');
  // Obtain the URI of the media asset.
W
wusongqing 已提交
666
});
667
```
W
wusongqing 已提交
668

G
Gloria 已提交
669
### storeMediaAsset
W
wusongqing 已提交
670 671 672

storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt;

A
Annie_wang 已提交
673
Stores a media asset. This API uses a promise to return the URI of the media asset.
W
wusongqing 已提交
674

A
Annie_wang 已提交
675
> **NOTE**<br>This API is supported since API version 6 and can be used only in the FA model.
W
wusongqing 已提交
676 677 678 679 680

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
681 682 683
| Name   | Type                                   | Mandatory  | Description     |
| ------ | ------------------------------------- | ---- | ------- |
| option | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.|
W
wusongqing 已提交
684 685 686

**Return value**

W
wusongqing 已提交
687 688
| Type                   | Description                          |
| --------------------- | ---------------------------- |
A
Annie_wang 已提交
689
| Promise&lt;string&gt; | Promise used to return the URI of the media asset saved.|
W
wusongqing 已提交
690 691 692

**Example**

693
```js
W
wusongqing 已提交
694
let option = {
A
Annie_wang 已提交
695 696 697
  src : '/data/storage/el2/base/haps/entry/image.png',
  mimeType : 'image/*',
  relativePath : 'Pictures/'
W
wusongqing 已提交
698 699
};
mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
A
Annie_wang 已提交
700 701
  console.info('Media resources stored.');
  // Obtain the URI of the media asset.
G
Gloria 已提交
702
}).catch((error) => {
A
Annie_wang 已提交
703
  console.error('storeMediaAsset failed with error: ' + error);
W
wusongqing 已提交
704
});
705
```
W
wusongqing 已提交
706

G
Gloria 已提交
707
### startImagePreview
W
wusongqing 已提交
708 709 710

startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
711
Starts 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 result.
W
wusongqing 已提交
712

W
wusongqing 已提交
713
> **NOTE**
A
Annie_wang 已提交
714 715
> This API is supported since API version 6 and can be used only in the FA model.
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images.
W
wusongqing 已提交
716 717 718 719 720

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
721 722
| Name     | Type                       | Mandatory  | Description                                      |
| -------- | ------------------------- | ---- | ---------------------------------------- |
G
Gloria 已提交
723
| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
W
wusongqing 已提交
724
| index    | number                    | Yes   | Index of the first image to preview.                              |
A
Annie_wang 已提交
725
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.                       |
W
wusongqing 已提交
726 727 728

**Example**

729
```js
W
wusongqing 已提交
730
let images = [
A
Annie_wang 已提交
731 732
  'file://media/xxxx/2',
  'file://media/xxxx/3'
W
wusongqing 已提交
733
];
W
wusongqing 已提交
734
/* Preview online images.
W
wusongqing 已提交
735
let images = [
A
Annie_wang 已提交
736 737
  'https://media.xxxx.com/image1.jpg',
  'https://media.xxxx.com/image2.jpg'
W
wusongqing 已提交
738
];
W
wusongqing 已提交
739
*/
W
wusongqing 已提交
740
let index = 1;
G
Gloria 已提交
741
mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
A
Annie_wang 已提交
742 743 744 745 746
  if (error) {
    console.error('startImagePreview failed with error: ' + error);
    return;
  }
  console.info('Succeeded in previewing the images.');
W
wusongqing 已提交
747
});
748
```
W
wusongqing 已提交
749

G
Gloria 已提交
750
### startImagePreview
W
wusongqing 已提交
751 752 753

startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
754
Starts 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 result.
W
wusongqing 已提交
755

W
wusongqing 已提交
756
> **NOTE**
A
Annie_wang 已提交
757 758
> This API is supported since API version 6 and can be used only in the FA model.
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images.
W
wusongqing 已提交
759 760 761 762 763

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
764 765
| Name     | Type                       | Mandatory  | Description                                      |
| -------- | ------------------------- | ---- | ---------------------------------------- |
G
Gloria 已提交
766
| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
A
Annie_wang 已提交
767
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.                       |
W
wusongqing 已提交
768 769 770

**Example**

771
```js
W
wusongqing 已提交
772
let images = [
A
Annie_wang 已提交
773 774
  'file://media/xxxx/2',
  'file://media/xxxx/3'
W
wusongqing 已提交
775
];
W
wusongqing 已提交
776
/* Preview online images.
W
wusongqing 已提交
777
let images = [
A
Annie_wang 已提交
778 779
  'https://media.xxxx.com/image1.jpg',
  'https://media.xxxx.com/image2.jpg'
W
wusongqing 已提交
780
];
W
wusongqing 已提交
781
*/
G
Gloria 已提交
782
mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
A
Annie_wang 已提交
783 784 785 786 787
  if (error) {
    console.error('startImagePreview failed with error: ' + error);
    return;
  }
  console.info('Succeeded in previewing the images.');
W
wusongqing 已提交
788
});
789
```
W
wusongqing 已提交
790

G
Gloria 已提交
791
### startImagePreview
W
wusongqing 已提交
792 793 794

startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void&gt;

795
Starts 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.
W
wusongqing 已提交
796

W
wusongqing 已提交
797
> **NOTE**
A
Annie_wang 已提交
798 799
> This API is supported since API version 6 and can be used only in the FA model.
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images.
W
wusongqing 已提交
800 801 802 803 804

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
805 806
| Name   | Type                 | Mandatory  | Description                                      |
| ------ | ------------------- | ---- | ---------------------------------------- |
G
Gloria 已提交
807
| images | Array&lt;string&gt; | Yes   | URIs of the images to preview. The value can start with either **'https://'** or **'datashare://'**.|
W
wusongqing 已提交
808
| index  | number              | No   | Index of the first image to preview. If this parameter is not specified, the default value **0** is used.                     |
W
wusongqing 已提交
809 810 811

**Return value**

W
wusongqing 已提交
812 813
| Type                 | Description                             |
| ------------------- | ------------------------------- |
A
Annie_wang 已提交
814
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
815 816 817

**Example**

818
```js
W
wusongqing 已提交
819
let images = [
A
Annie_wang 已提交
820 821
  'file://media/xxxx/2',
  'file://media/xxxx/3'
W
wusongqing 已提交
822
];
W
wusongqing 已提交
823
/* Preview online images.
W
wusongqing 已提交
824
let images = [
A
Annie_wang 已提交
825 826
  'https://media.xxxx.com/image1.jpg',
  'https://media.xxxx.com/image2.jpg'
W
wusongqing 已提交
827
];
W
wusongqing 已提交
828
*/
W
wusongqing 已提交
829 830
let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
A
Annie_wang 已提交
831
  console.info('Succeeded in previewing the images.');
G
Gloria 已提交
832
}).catch((error) => {
A
Annie_wang 已提交
833
  console.error('startImagePreview failed with error: ' + error);
W
wusongqing 已提交
834
});
835
```
W
wusongqing 已提交
836

G
Gloria 已提交
837
### startMediaSelect
W
wusongqing 已提交
838 839 840

startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void

A
Annie_wang 已提交
841
Starts media selection. This API uses an asynchronous callback to return the URIs of the selected media assets.
W
wusongqing 已提交
842

W
wusongqing 已提交
843
> **NOTE**
A
Annie_wang 已提交
844 845
> This API is supported since API version 6 and can be used only in the FA model.
> 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, see [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
W
wusongqing 已提交
846 847 848 849 850

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
851 852
| Name     | Type                                      | Mandatory  | Description                                  |
| -------- | ---------------------------------------- | ---- | ------------------------------------ |
G
Gloria 已提交
853
| option   | [MediaSelectOption](#mediaselectoption)  | Yes   | Media selection option.                             |
A
Annie_wang 已提交
854
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes   | Callback invoked to return the URIs of the selected media assets.|
W
wusongqing 已提交
855 856 857

**Example**

858 859
```js
let option : mediaLibrary.MediaSelectOption = {
A
Annie_wang 已提交
860 861
  type : 'media',
  count : 2
W
wusongqing 已提交
862
};
G
Gloria 已提交
863
mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => {
A
Annie_wang 已提交
864 865 866 867 868 869
  if (error) {
    console.error('startMediaSelect failed with error: ' + error);
    return;
  }
  console.info('Media resources selected.');
  // Obtain the media selection value.
W
wusongqing 已提交
870
});
871
```
W
wusongqing 已提交
872

G
Gloria 已提交
873
### startMediaSelect
W
wusongqing 已提交
874 875 876

startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt;

A
Annie_wang 已提交
877
Starts media selection. This API uses a promise to return the URIs of the selected media assets.
W
wusongqing 已提交
878

W
wusongqing 已提交
879
> **NOTE**
A
Annie_wang 已提交
880 881
> This API is supported since API version 6 and can be used only in the FA model.
> 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, see [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
W
wusongqing 已提交
882 883 884 885 886

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
887 888
| Name   | Type                                     | Mandatory  | Description     |
| ------ | --------------------------------------- | ---- | ------- |
G
Gloria 已提交
889
| option | [MediaSelectOption](#mediaselectoption) | Yes   | Media selection option.|
W
wusongqing 已提交
890 891 892

**Return value**

W
wusongqing 已提交
893 894
| Type                                | Description                                      |
| ---------------------------------- | ---------------------------------------- |
A
Annie_wang 已提交
895
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the URIs of the selected media assets.|
W
wusongqing 已提交
896 897 898

**Example**

899 900
```js
let option : mediaLibrary.MediaSelectOption = {
A
Annie_wang 已提交
901 902
  type : 'media',
  count : 2
W
wusongqing 已提交
903 904
};
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
A
Annie_wang 已提交
905 906
  console.info('Media resources selected.');
  // Obtain the media selection value.
G
Gloria 已提交
907
}).catch((error) => {
A
Annie_wang 已提交
908
  console.error('startMediaSelect failed with error: ' + error);
W
wusongqing 已提交
909
});
910
```
A
Annie_wang 已提交
911

912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
### getActivePeers<sup>8+</sup>

getActivePeers(): Promise\<Array\<PeerInfo>>;

Obtains information about online peer devices. This API uses a promise to return the result.

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore

**Return value**

| Type                 | Description                  |
| ------------------- | -------------------- |
G
gloria 已提交
928
|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
929 930 931 932 933

**Example**

```js
async function example() {
A
Annie_wang 已提交
934 935 936 937 938 939 940 941 942
  media.getActivePeers().then((devicesInfo) => {
    if (devicesInfo != undefined) {
      console.info('get distributed info ' + JSON.stringify(devicesInfo));
    } else {
      console.info('get distributed info is undefined!');
    }
  }).catch((error) => {
    console.error('get distributed info failed with error: ' + error);
  });
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
}
```

### getActivePeers<sup>8+</sup>

getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;

Obtains information about online peer devices. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore

**Return value**

| Type                 | Description                  |
| ------------------- | -------------------- |
A
Annie_wang 已提交
962
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Callback invoked to return the online peer devices, in an array of **PeerInfo** objects.|
963 964 965 966 967

**Example**

```js
async function example() {
A
Annie_wang 已提交
968 969 970 971 972 973 974
  media.getActivePeers((error, devicesInfo) => {
    if (devicesInfo != undefined) {
      console.info('get distributed info ' + JSON.stringify(devicesInfo));
    } else {
      console.error('get distributed failed with error: ' + error);
    }
  });
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
}
```

### getAllPeers<sup>8+</sup>

getAllPeers(): Promise\<Array\<PeerInfo>>;

Obtains information about all peer devices. This API uses a promise to return the result.

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore

**Return value**

| Type                 | Description                  |
| ------------------- | -------------------- |
G
gloria 已提交
994
|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
995 996 997 998 999

**Example**

```js
async function example() {
A
Annie_wang 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008
  media.getAllPeers().then((devicesInfo) => {
    if (devicesInfo != undefined) {
      console.info('get distributed info ' + JSON.stringify(devicesInfo));
    } else {
      console.info('get distributed info is undefined!');
    }
  }).catch((error) => {
    console.error('get distributed info failed with error: ' + error);
  });
1009 1010 1011 1012 1013 1014 1015
}
```

### getAllPeers<sup>8+</sup>

getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;

A
Annie_wang 已提交
1016
Obtains information about all peer devices. This API uses an asynchronous callback to return the result.
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

**System API**: This is a system API.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore

**Return value**

| Type                 | Description                  |
| ------------------- | -------------------- |
A
Annie_wang 已提交
1028
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Callback invoked to return all peer devices, in an array of **PeerInfo** objects.|
1029 1030 1031 1032 1033

**Example**

```js
async function example() {
A
Annie_wang 已提交
1034 1035 1036 1037 1038 1039 1040
  media.getAllPeers((error, devicesInfo) => {
    if (devicesInfo != undefined) {
      console.info('get distributed info ' + JSON.stringify(devicesInfo));
    } else {
      console.error('get distributed failed with error: ' + error);
    }
  });
1041 1042
}
```
W
wusongqing 已提交
1043

W
wusongqing 已提交
1044
## FileAsset<sup>7+</sup>
W
wusongqing 已提交
1045 1046 1047

Provides APIs for encapsulating file asset attributes.

G
gloria 已提交
1048
> **NOTE**
A
Annie_wang 已提交
1049
>
G
gloria 已提交
1050 1051 1052
> 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.
> 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.

W
wusongqing 已提交
1053 1054 1055 1056
### Attributes

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

W
wusongqing 已提交
1057
| Name                     | Type                    | Readable| Writable| Description                                                  |
W
wusongqing 已提交
1058
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
W
wusongqing 已提交
1059
| id                        | number                   | Yes  | No  | File asset ID.                                          |
L
lvyuanyuan 已提交
1060
| uri                       | string                   | Yes  | No  | File asset URI, for example, **file://media/image/2**.        |
W
wusongqing 已提交
1061 1062
| mimeType                  | string                   | Yes  | No  | Extended file attributes.                                          |
| mediaType<sup>8+</sup>    | [MediaType](#mediatype8) | Yes  | No  | Media type.                                              |
A
Annie_wang 已提交
1063 1064 1065 1066
| displayName               | string                   | Yes  | Yes  | File name, including the file name extension, to display.                                |
| title                     | string                   | Yes  | Yes  | Title in the file.                                              |
| relativePath<sup>8+</sup> | string                   | Yes  | Yes  | Relative path of the user directory.                                      |
| parent<sup>8+</sup>       | number                   | Yes  | No  | Parent directory ID. Since SDK of API version 10, an asset can exist in multiple albums. Therefore, this attribute is incompatible. The obtained value is always **0**.                       |
W
wusongqing 已提交
1067
| size                      | number                   | Yes  | No  | File size, in bytes.                                |
G
Gloria 已提交
1068 1069 1070
| dateAdded                 | number                   | Yes  | No  | Date when the file was added. The value is the number of seconds elapsed since the Epoch time.        |
| 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.|
| dateTaken                 | number                   | Yes  | No  | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time.        |
W
wusongqing 已提交
1071 1072 1073 1074 1075
| artist<sup>8+</sup>       | string                   | Yes  | No  | Artist of the file.                                                  |
| audioAlbum<sup>8+</sup>   | string                   | Yes  | No  | Audio album.                                                  |
| width                     | number                   | Yes  | No  | Image width, in pixels.                                |
| height                    | number                   | Yes  | No  | Image height, in pixels.                                |
| orientation               | number                   | Yes  | Yes  | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).|
W
wusongqing 已提交
1076
| duration<sup>8+</sup>     | number                   | Yes  | No  | Duration, in ms.                                  |
A
Annie_wang 已提交
1077 1078 1079
| albumId                   | number                   | Yes  | No  | ID of the album to which the file belongs. Since SDK of API version 10, an asset can exist in multiple albums. Therefore, this attribute is incompatible. The obtained value is always **0**.                  |
| albumUri<sup>8+</sup>     | string                   | Yes  | No  | URI of the album to which the file belongs. Since SDK of API version 10, an asset can exist in multiple albums. Therefore, this attribute is incompatible. The obtained value is always an empty string.                     |
| albumName                 | string                   | Yes  | No  | Name of the album to which the file belongs. Since SDK of API version 10, an asset can exist in multiple albums. Therefore, this attribute is incompatible. The obtained value is always an empty string.                    |
W
wusongqing 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

### isDirectory<sup>8+</sup>

isDirectory(callback: AsyncCallback&lt;boolean&gt;): void

Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1093
| Name     | Type                          | Mandatory  | Description                 |
W
wusongqing 已提交
1094
| -------- | ---------------------------- | ---- | ------------------- |
A
Annie_wang 已提交
1095
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback invoked to return the result. The value **true** means the file asset is a directory; the value false means the opposite.|
W
wusongqing 已提交
1096 1097 1098

**Example**

1099
```js
W
wusongqing 已提交
1100
async function example() {
A
Annie_wang 已提交
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isDirectory((error, isDirectory) => {
    if (error) {
      console.error('isDirectory failed with error: ' + error);
    } else {
      console.info('isDirectory result:' + isDirectory);
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
}
```

### isDirectory<sup>8+</sup>

isDirectory():Promise&lt;boolean&gt;

Checks whether this file asset is a directory. This API uses a promise to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1133 1134
| Type                    | Description                          |
| ---------------------- | ---------------------------- |
A
Annie_wang 已提交
1135
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the file asset is a directory; the value **false** means the opposite.|
W
wusongqing 已提交
1136 1137 1138

**Example**

1139
```js
W
wusongqing 已提交
1140
async function example() {
A
Annie_wang 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isDirectory().then((isDirectory) => {
    console.info('isDirectory result:' + isDirectory);
  }).catch((error) => {
    console.error('isDirectory failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1156 1157 1158 1159 1160 1161 1162
}
```

### commitModify<sup>8+</sup>

commitModify(callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
1163 1164 1165 1166
Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result.

> **NOTE**
> Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
W
wusongqing 已提交
1167 1168 1169 1170 1171 1172 1173

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1174 1175
| Name     | Type                       | Mandatory  | Description   |
| -------- | ------------------------- | ---- | ----- |
A
Annie_wang 已提交
1176
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.|
W
wusongqing 已提交
1177 1178 1179

**Example**

1180
```js
W
wusongqing 已提交
1181
async function example() {
A
Annie_wang 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.title = 'newtitle';
  asset.commitModify(() => {
    console.info('commitModify successfully');
  });
  fetchFileResult.close();
W
wusongqing 已提交
1196 1197 1198 1199 1200 1201 1202
}
```

### commitModify<sup>8+</sup>

commitModify(): Promise&lt;void&gt;

A
Annie_wang 已提交
1203 1204 1205 1206
Commits the modification on the file asset to the database. This API uses a promise to return the result.

> **NOTE**
> Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
W
wusongqing 已提交
1207 1208 1209 1210 1211 1212 1213

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1214 1215
| Type                 | Description        |
| ------------------- | ---------- |
A
Annie_wang 已提交
1216
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
1217 1218 1219

**Example**

1220
```js
W
wusongqing 已提交
1221
async function example() {
A
Annie_wang 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.title = 'newtitle';
  await asset.commitModify();
  fetchFileResult.close();
W
wusongqing 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242
}
```

### open<sup>8+</sup>

open(mode: string, callback: AsyncCallback&lt;number&gt;): void

Opens this file asset. This API uses an asynchronous callback to return the result.

A
Annie_wang 已提交
1243
**NOTE**<br>If a file is opened in 'w' mode, the returned file descriptor (FD) cannot be used to read the file. 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 close the file.
W
wusongqing 已提交
1244

W
wusongqing 已提交
1245
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1246 1247 1248 1249 1250

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1251 1252
| Name     | Type                         | Mandatory  | Description                                 |
| -------- | --------------------------- | ---- | ----------------------------------- |
A
Annie_wang 已提交
1253 1254
| mode     | string                      | Yes   | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).|
| callback | AsyncCallback&lt;number&gt; | Yes   | Callback invoked to return the FD of the file opened.                           |
W
wusongqing 已提交
1255 1256 1257

**Example**

1258
```js
W
wusongqing 已提交
1259
async function example() {
A
Annie_wang 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
  let mediaType = mediaLibrary.MediaType.IMAGE;
  let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
  const path = await media.getPublicDirectory(DIR_IMAGE);
  const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
  asset.open('rw', (error, fd) => {
    if (fd > 0) {
      asset.close(fd);
    } else {
      console.error('File Open failed with error: ' + error);
    }
  });
W
wusongqing 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279
}
```

### open<sup>8+</sup>

open(mode: string): Promise&lt;number&gt;

Opens this file asset. This API uses a promise to return the result.

A
Annie_wang 已提交
1280
**NOTE**<br>If a file is opened in 'w' mode, the returned FD cannot be used to read the file. 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 close the file.
W
wusongqing 已提交
1281

W
wusongqing 已提交
1282
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1283 1284 1285 1286 1287

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1288 1289
| Name | Type    | Mandatory  | Description                                 |
| ---- | ------ | ---- | ----------------------------------- |
A
Annie_wang 已提交
1290
| mode | string | Yes   | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).|
W
wusongqing 已提交
1291 1292 1293

**Return value**

W
wusongqing 已提交
1294 1295
| Type                   | Description           |
| --------------------- | ------------- |
A
Annie_wang 已提交
1296
| Promise&lt;number&gt; | Promise used to return the FD of the file opened.|
W
wusongqing 已提交
1297 1298 1299

**Example**

1300
```js
W
wusongqing 已提交
1301
async function example() {
A
Annie_wang 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310
  let mediaType = mediaLibrary.MediaType.IMAGE;
  let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
  const path = await media.getPublicDirectory(DIR_IMAGE);
  const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
  asset.open('rw').then((fd) => {
    console.info('File open fd: ' + fd);
  }).catch((error) => {
    console.error('File open failed with error: ' + error);
  });
W
wusongqing 已提交
1311 1312 1313 1314 1315 1316 1317
}
```

### close<sup>8+</sup>

close(fd: number, callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
1318
Closes a file. This API uses an asynchronous callback to return the result.
W
wusongqing 已提交
1319

W
wusongqing 已提交
1320
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1321 1322 1323 1324 1325

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1326 1327
| Name     | Type                       | Mandatory  | Description   |
| -------- | ------------------------- | ---- | ----- |
A
Annie_wang 已提交
1328 1329
| fd       | number                    | Yes   | FD of the file to close.|
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.|
W
wusongqing 已提交
1330 1331 1332

**Example**

1333
```js
W
wusongqing 已提交
1334
async function example() {
A
Annie_wang 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.open('rw').then((fd) => {
    console.info('File open fd: ' + fd);
    asset.close(fd, (error) => {
      if (error) {
        console.error('asset.close failed with error: ' + error);
      } else {
        console.info('asset.close successfully');
      }
W
wusongqing 已提交
1352
    });
A
Annie_wang 已提交
1353 1354 1355 1356
  }).catch((error) => {
    console.error('File open failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1357 1358 1359 1360 1361 1362 1363
}
```

### close<sup>8+</sup>

close(fd: number): Promise&lt;void&gt;

A
Annie_wang 已提交
1364
Closes a file. This API uses a promise to return the result.
W
wusongqing 已提交
1365

W
wusongqing 已提交
1366
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1367 1368 1369 1370 1371

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1372 1373
| Name | Type    | Mandatory  | Description   |
| ---- | ------ | ---- | ----- |
A
Annie_wang 已提交
1374
| fd   | number | Yes   | FD of the file to close.|
W
wusongqing 已提交
1375 1376 1377

**Return value**

W
wusongqing 已提交
1378 1379
| Type                 | Description        |
| ------------------- | ---------- |
A
Annie_wang 已提交
1380
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
1381 1382 1383

**Example**

1384
```js
W
wusongqing 已提交
1385
async function example() {
A
Annie_wang 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.open('rw').then((fd) => {
    console.info('File fd!' + fd);
    asset.close(fd).then(() => {
      console.info('asset.close successfully');
    }).catch((closeErr) => {
      console.error('asset.close fail, closeErr: ' + closeErr);
W
wusongqing 已提交
1401
    });
A
Annie_wang 已提交
1402 1403 1404 1405
  }).catch((error) => {
    console.error('open File failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
}
```

### getThumbnail<sup>8+</sup>

getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void

Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1421 1422
| Name     | Type                                 | Mandatory  | Description              |
| -------- | ----------------------------------- | ---- | ---------------- |
A
Annie_wang 已提交
1423
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback invoked to return the PixelMap of the thumbnail.|
W
wusongqing 已提交
1424 1425 1426

**Example**

1427
```js
W
wusongqing 已提交
1428
async function example() {
A
Annie_wang 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.getThumbnail((error, pixelmap) => {
    if (error) {
      console.error('mediaLibrary getThumbnail failed with error: ' + error);
    } else {
      console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1446 1447 1448 1449 1450 1451 1452
}
```

### getThumbnail<sup>8+</sup>

getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void

A
Annie_wang 已提交
1453
Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result.
W
wusongqing 已提交
1454 1455 1456 1457 1458 1459 1460

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1461 1462 1463
| Name     | Type                                 | Mandatory  | Description              |
| -------- | ----------------------------------- | ---- | ---------------- |
| size     | [Size](#size8)                      | Yes   | Size of the thumbnail.           |
A
Annie_wang 已提交
1464
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback invoked to return the PixelMap of the thumbnail.|
W
wusongqing 已提交
1465 1466 1467

**Example**

1468
```js
W
wusongqing 已提交
1469
async function example() {
A
Annie_wang 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let size = { width: 720, height: 720 };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.getThumbnail(size, (error, pixelmap) => {
    if (error) {
      console.error('mediaLibrary getThumbnail failed with error: ' + error);
    } else {
      console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1488 1489 1490 1491 1492 1493 1494
}
```

### getThumbnail<sup>8+</sup>

getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt;

A
Annie_wang 已提交
1495
Obtains the file thumbnail of the given size. This API uses a promise to return the result.
W
wusongqing 已提交
1496 1497 1498 1499 1500 1501 1502

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1503 1504 1505
| Name | Type            | Mandatory  | Description   |
| ---- | -------------- | ---- | ----- |
| size | [Size](#size8) | No   | Size of the thumbnail.|
W
wusongqing 已提交
1506 1507 1508

**Return value**

W
wusongqing 已提交
1509 1510
| Type                           | Description                   |
| ----------------------------- | --------------------- |
A
Annie_wang 已提交
1511
| Promise&lt;image.PixelMap&gt; | Promise used to return the PixelMap of the thumbnail.|
W
wusongqing 已提交
1512 1513 1514

**Example**

1515
```js
W
wusongqing 已提交
1516
async function example() {
A
Annie_wang 已提交
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let size = { width: 720, height: 720 };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.getThumbnail(size).then((pixelmap) => {
    console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
  }).catch((error) => {
    console.error('mediaLibrary getThumbnail failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
}
```

### favorite<sup>8+</sup>

favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void

Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1548 1549
| Name       | Type                       | Mandatory  | Description                                |
| ---------- | ------------------------- | ---- | ---------------------------------- |
A
Annie_wang 已提交
1550 1551
| isFavorite | boolean                   | Yes   | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.|
| callback   | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.                             |
W
wusongqing 已提交
1552 1553 1554

**Example**

1555
```js
W
wusongqing 已提交
1556
async function example() {
A
Annie_wang 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.favorite(true,(error) => {
    if (error) {
      console.error('mediaLibrary favorite failed with error: ' + error);
    } else {
      console.info('mediaLibrary favorite Successful');
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
}
```

### favorite<sup>8+</sup>

favorite(isFavorite: boolean): Promise&lt;void&gt;

Favorites or unfavorites this file asset. This API uses a promise to return the result.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1589 1590
| Name       | Type     | Mandatory  | Description                                |
| ---------- | ------- | ---- | ---------------------------------- |
A
Annie_wang 已提交
1591
| isFavorite | boolean | Yes   | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.|
W
wusongqing 已提交
1592 1593 1594

**Return value**

W
wusongqing 已提交
1595 1596
| Type                 | Description        |
| ------------------- | ---------- |
A
Annie_wang 已提交
1597
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
1598 1599 1600

**Example**

1601
```js
W
wusongqing 已提交
1602
async function example() {
A
Annie_wang 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.favorite(true).then(() => {
    console.info('mediaLibrary favorite Successful');
  }).catch((error) => {
    console.error('mediaLibrary favorite failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
}
```

### isFavorite<sup>8+</sup>

isFavorite(callback: AsyncCallback&lt;boolean&gt;): void

Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1633 1634
| Name     | Type                          | Mandatory  | Description         |
| -------- | ---------------------------- | ---- | ----------- |
A
Annie_wang 已提交
1635
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback invoked to return the result. The value **true** means the file asset is favorited; the value **false** means the opposite.|
W
wusongqing 已提交
1636 1637 1638

**Example**

1639
```js
W
wusongqing 已提交
1640
async function example() {
A
Annie_wang 已提交
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isFavorite((error, isFavorite) => {
    if (error) {
      console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
    } else {
      console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
}
```

### isFavorite<sup>8+</sup>

isFavorite():Promise&lt;boolean&gt;

Checks whether this file asset is favorited. This API uses a promise to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1673 1674
| Type                    | Description                |
| ---------------------- | ------------------ |
A
Annie_wang 已提交
1675
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means the file asset is favorited; the value **false** means the opposite.|
W
wusongqing 已提交
1676 1677 1678

**Example**

1679
```js
W
wusongqing 已提交
1680
async function example() {
A
Annie_wang 已提交
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isFavorite().then((isFavorite) => {
    console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
  }).catch((error) => {
    console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
}
```

### trash<sup>8+</sup>

trash(isTrash: boolean, callback: AsyncCallback&lt;void&gt;): void

Moves this file asset to the trash. This API uses an asynchronous callback to return the result.

Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1713 1714
| Name     | Type                       | Mandatory  | Description       |
| -------- | ------------------------- | ---- | --------- |
A
Annie_wang 已提交
1715 1716
| isTrash  | boolean                   | Yes   | Whether to move the file asset to the trash.|
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback that returns no value.    |
W
wusongqing 已提交
1717 1718 1719

**Example**

1720
```js
W
wusongqing 已提交
1721
async function example() {
A
Annie_wang 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.trash(true, (error) => {
    if (error) {
      console.error('mediaLibrary trash failed with error: ' + error);
    } else {
      console.info('mediaLibrary trash Successful');
    }
  });
  fetchFileResult.close();
W
wusongqing 已提交
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
}
```

### trash<sup>8+</sup>

trash(isTrash: boolean): Promise&lt;void&gt;

Moves this file asset to the trash. This API uses a promise to return the result.

Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1756 1757
| Name    | Type     | Mandatory  | Description       |
| ------- | ------- | ---- | --------- |
A
Annie_wang 已提交
1758
| isTrash | boolean | Yes   | Whether to move the file asset to the trash.|
W
wusongqing 已提交
1759 1760 1761

**Return value**

W
wusongqing 已提交
1762 1763
| Type                 | Description        |
| ------------------- | ---------- |
A
Annie_wang 已提交
1764
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
1765 1766 1767

**Example**

1768
```js
W
wusongqing 已提交
1769
async function example() {
A
Annie_wang 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.trash(true).then(() => {
    console.info('trash successfully');
  }).catch((error) => {
    console.error('trash failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
}
```

### isTrash<sup>8+</sup>

isTrash(callback: AsyncCallback&lt;boolean&gt;): void

Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1800 1801
| Name     | Type                          | Mandatory  | Description             |
| -------- | ---------------------------- | ---- | --------------- |
A
Annie_wang 已提交
1802
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback invoked to return the result. The value **true** means the file is in the trash; the value **false** means the opposite.|
W
wusongqing 已提交
1803 1804 1805

**Example**

1806
```js
W
wusongqing 已提交
1807
async function example() {
A
Annie_wang 已提交
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isTrash((error, isTrash) => {
    if (error) {
      console.error('Failed to get trash state failed with error: ' + error);
      return;
    }
    console.info('Get trash state successfully, isTrash result: ' + isTrash);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
}
```

### isTrash<sup>8+</sup>

isTrash():Promise&lt;boolean&gt;

Checks whether this file asset is in the trash. This API uses a promise to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1840 1841
| Type                 | Description                  |
| ------------------- | -------------------- |
A
Annie_wang 已提交
1842
| Promise&lt;void&gt; | Promise used to return the result. The value **true** means the file is in the trash; the value **false** means the opposite.|
W
wusongqing 已提交
1843 1844 1845

**Example**

1846
```js
W
wusongqing 已提交
1847
async function example() {
A
Annie_wang 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  const fetchFileResult = await media.getFileAssets(getImageOp);
  const asset = await fetchFileResult.getFirstObject();
  asset.isTrash().then((isTrash) => {
    console.info('isTrash result: ' + isTrash);
  }).catch((error) => {
    console.error('isTrash failed with error: ' + error);
  });
  fetchFileResult.close();
W
wusongqing 已提交
1863 1864 1865
}
```

W
wusongqing 已提交
1866
## FetchFileResult<sup>7+</sup>
W
wusongqing 已提交
1867

A
Annie_wang 已提交
1868
Provides APIs to manage the file retrieval result.
W
wusongqing 已提交
1869

W
wusongqing 已提交
1870
### getCount<sup>7+</sup>
W
wusongqing 已提交
1871 1872 1873 1874 1875 1876 1877 1878 1879

getCount(): number

Obtains the total number of files in the result set.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1880 1881
| Type    | Description      |
| ------ | -------- |
A
Annie_wang 已提交
1882
| number | Returns the total number of files obtained.|
W
wusongqing 已提交
1883 1884 1885

**Example**

1886
```js
W
wusongqing 已提交
1887
async function example() {
A
Annie_wang 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.FILE;
  let getFileCountOneOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
  const fetchCount = fetchFileResult.getCount();
  console.info('fetchCount result: ' + fetchCount);
  fetchFileResult.close();
W
wusongqing 已提交
1899 1900 1901
}
```

W
wusongqing 已提交
1902
### isAfterLast<sup>7+</sup>
W
wusongqing 已提交
1903 1904 1905 1906 1907 1908 1909 1910 1911

isAfterLast(): boolean

Checks whether the cursor is in the last row of the result set.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
1912 1913
| Type     | Description                                |
| ------- | ---------------------------------- |
A
Annie_wang 已提交
1914
| boolean | Returns **true** if the cursor is in the last row of the result set; returns **false** otherwise.|
W
wusongqing 已提交
1915 1916 1917

**Example**

1918
```js
W
wusongqing 已提交
1919
async function example() {
A
Annie_wang 已提交
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  const fetchCount = fetchFileResult.getCount();
  console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount);
  let fileAsset = await fetchFileResult.getFirstObject();
  for (var i = 1; i < fetchCount; i++) {
    fileAsset = await fetchFileResult.getNextObject();
    if(i == fetchCount - 1) {
      var result = fetchFileResult.isAfterLast();
      console.info('mediaLibrary fileAsset isAfterLast result: ' + result);
      fetchFileResult.close();
W
wusongqing 已提交
1937
    }
A
Annie_wang 已提交
1938
  }
W
wusongqing 已提交
1939 1940 1941
}
```

W
wusongqing 已提交
1942
### close<sup>7+</sup>
W
wusongqing 已提交
1943 1944 1945

close(): void

A
Annie_wang 已提交
1946
Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked.
W
wusongqing 已提交
1947 1948 1949 1950 1951

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Example**

1952
```js
W
wusongqing 已提交
1953
async function example() {
A
Annie_wang 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.close();
W
wusongqing 已提交
1963 1964 1965
}
```

W
wusongqing 已提交
1966
### getFirstObject<sup>7+</sup>
W
wusongqing 已提交
1967 1968 1969 1970 1971 1972 1973 1974 1975

getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void

Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
1976 1977
| Name  | Type                                         | Mandatory| Description                                       |
| -------- | --------------------------------------------- | ---- | ------------------------------------------- |
A
Annie_wang 已提交
1978
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback invoked to return the first **FileAsset** object in the result set.|
W
wusongqing 已提交
1979 1980 1981

**Example**

1982
```js
W
wusongqing 已提交
1983
async function example() {
A
Annie_wang 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getFirstObject((error, fileAsset) => {
    if (error) {
      console.error('fetchFileResult getFirstObject failed with error: ' + error);
      return;
    }
    console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName);
    fetchFileResult.close();
  })
W
wusongqing 已提交
2000 2001 2002
}
```

W
wusongqing 已提交
2003
### getFirstObject<sup>7+</sup>
W
wusongqing 已提交
2004 2005 2006 2007 2008 2009 2010 2011 2012

getFirstObject(): Promise&lt;FileAsset&gt;

Obtains the first file asset in the result set. This API uses a promise to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
2013 2014
| Type                                   | Description                      |
| --------------------------------------- | -------------------------- |
A
Annie_wang 已提交
2015
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the first **FileAsset** object in the result set.|
W
wusongqing 已提交
2016 2017 2018

**Example**

2019
```js
W
wusongqing 已提交
2020
async function example() {
A
Annie_wang 已提交
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getFirstObject().then((fileAsset) => {
    console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName);
    fetchFileResult.close();
  }).catch((error) => {
    console.error('getFirstObject failed with error: ' + error);
  });
W
wusongqing 已提交
2035 2036 2037
}
```

W
wusongqing 已提交
2038
### getNextObject<sup>7+</sup>
W
wusongqing 已提交
2039

2040
getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
W
wusongqing 已提交
2041 2042

Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2043 2044

> **NOTE**<br>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.
W
wusongqing 已提交
2045 2046 2047 2048 2049

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2050 2051
| Name   | Type                                         | Mandatory| Description                                     |
| --------- | --------------------------------------------- | ---- | ----------------------------------------- |
A
Annie_wang 已提交
2052
| callbacke | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback invoked to return the next **FileAsset** object in the result set.|
W
wusongqing 已提交
2053 2054 2055

**Example**

2056
```js
W
wusongqing 已提交
2057
async function example() {
A
Annie_wang 已提交
2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  let fileAsset = await fetchFileResult.getFirstObject();
  console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
  if (!fetchFileResult.isAfterLast()) {
    fetchFileResult.getNextObject((error, fileAsset) => {
      if (error) {
        console.error('fetchFileResult getNextObject failed with error: ' + error);
        return;
      }
      console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
      fetchFileResult.close();
    })
  }
W
wusongqing 已提交
2078
}
G
Gloria 已提交
2079

W
wusongqing 已提交
2080 2081
```

W
wusongqing 已提交
2082
### getNextObject<sup>7+</sup>
W
wusongqing 已提交
2083

2084
getNextObject(): Promise&lt;FileAsset&gt;
W
wusongqing 已提交
2085 2086

Obtains the next file asset in the result set. This API uses a promise to return the result.
A
Annie_wang 已提交
2087 2088

> **NOTE**<br>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.
W
wusongqing 已提交
2089 2090 2091 2092 2093

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
2094 2095
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
A
Annie_wang 已提交
2096
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next **FileAsset** object in the result set.|
W
wusongqing 已提交
2097 2098 2099

**Example**

2100
```js
W
wusongqing 已提交
2101
async function example() {
A
Annie_wang 已提交
2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  let fileAsset = await fetchFileResult.getFirstObject();
  console.log('fetchFileResult getFirstObject successfully, displayName: ' + fileAsset.displayName);
  if (!fetchFileResult.isAfterLast()) {
    fetchFileResult.getNextObject().then((fileAsset) => {
      console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
      fetchFileResult.close();
    }).catch((error) => {
      console.error('fetchFileResult getNextObject failed with error: ' + error);
    })
  }
W
wusongqing 已提交
2120 2121 2122
}
```

W
wusongqing 已提交
2123
### getLastObject<sup>7+</sup>
W
wusongqing 已提交
2124 2125 2126 2127 2128 2129 2130 2131 2132

getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void

Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2133 2134
| Name  | Type                                         | Mandatory| Description                       |
| -------- | --------------------------------------------- | ---- | --------------------------- |
A
Annie_wang 已提交
2135
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback invoked to return the last **FileAsset** object in the result set.|
W
wusongqing 已提交
2136 2137 2138

**Example**

2139
```js
W
wusongqing 已提交
2140
async function example() {
A
Annie_wang 已提交
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getLastObject((error, fileAsset) => {
    if (error) {
      console.error('getLastObject failed with error: ' + error);
      return;
    }
    console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
    fetchFileResult.close();
  })
W
wusongqing 已提交
2157 2158 2159
}
```

W
wusongqing 已提交
2160
### getLastObject<sup>7+</sup>
W
wusongqing 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169

getLastObject(): Promise&lt;FileAsset&gt;

Obtains the last file asset in the result set. This API uses a promise to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
2170 2171
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
A
Annie_wang 已提交
2172
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the last **FileAsset** object in the result set.|
W
wusongqing 已提交
2173 2174 2175

**Example**

2176
```js
W
wusongqing 已提交
2177
async function example() {
A
Annie_wang 已提交
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getLastObject().then((fileAsset) => {
    console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
    fetchFileResult.close();
  }).catch((error) => {
    console.error('getLastObject failed with error: ' + error);
  });
W
wusongqing 已提交
2192 2193 2194
}
```

W
wusongqing 已提交
2195
### getPositionObject<sup>7+</sup>
W
wusongqing 已提交
2196 2197 2198 2199 2200 2201 2202 2203 2204

getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void

Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2205 2206
| Name      | Type                                      | Mandatory  | Description                |
| -------- | ---------------------------------------- | ---- | ------------------ |
G
Gloria 已提交
2207
| 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.    |
A
Annie_wang 已提交
2208
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes   | Callback invoked to return the **FileAsset** object with the specified index obtained.|
W
wusongqing 已提交
2209 2210 2211

**Example**

2212
```js
W
wusongqing 已提交
2213
async function example() {
A
Annie_wang 已提交
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getPositionObject(0, (error, fileAsset) => {
    if (error) {
      console.error('getPositionObject failed with error: ' + error);
      return;
    }
    console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
    fetchFileResult.close();
  })
W
wusongqing 已提交
2230 2231 2232
}
```

W
wusongqing 已提交
2233
### getPositionObject<sup>7+</sup>
W
wusongqing 已提交
2234 2235 2236 2237 2238 2239 2240 2241 2242

getPositionObject(index: number): Promise&lt;FileAsset&gt;

Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2243 2244
| Name   | Type    | Mandatory  | Description            |
| ----- | ------ | ---- | -------------- |
G
Gloria 已提交
2245
| 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.|
W
wusongqing 已提交
2246 2247 2248

**Return value**

W
wusongqing 已提交
2249 2250
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
A
Annie_wang 已提交
2251
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the **FileAsset** object with the specified index obtained.|
W
wusongqing 已提交
2252 2253 2254

**Example**

2255
```js
W
wusongqing 已提交
2256
async function example() {
A
Annie_wang 已提交
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getPositionObject(0).then((fileAsset) => {
    console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
    fetchFileResult.close();
  }).catch((error) => {
    console.error('getPositionObject failed with error: ' + error);
  });
W
wusongqing 已提交
2271 2272 2273
}
```

W
wusongqing 已提交
2274
### getAllObject<sup>7+</sup>
W
wusongqing 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283

getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void

Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2284 2285
| Name      | Type                                      | Mandatory  | Description                  |
| -------- | ---------------------------------------- | ---- | -------------------- |
A
Annie_wang 已提交
2286
| callback | AsyncCallback&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | Yes   | Callback invoked to return all the **FileAsset** objects in the result reset.|
W
wusongqing 已提交
2287 2288 2289

**Example**

2290
```js
W
wusongqing 已提交
2291
async function example() {
A
Annie_wang 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getAllObject((error, fileAssetList) => {
    if (error) {
      console.error('getAllObject failed with error: ' + error);
      return;
    }
    for (let i = 0; i < fetchFileResult.getCount(); i++) {
      console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
    }
    fetchFileResult.close();
  })
W
wusongqing 已提交
2310 2311 2312
}
```

W
wusongqing 已提交
2313
### getAllObject<sup>7+</sup>
W
wusongqing 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322

getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt;

Obtains all the file assets in the result set. This API uses a promise to return the result.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
2323 2324
| Type                                    | Description                 |
| ---------------------------------------- | --------------------- |
A
Annie_wang 已提交
2325
| Promise&lt;Array&lt;[FileAsset](#fileasset7)&gt;&gt; | Promise used to return all the **FileAsset** objects in the result reset.|
W
wusongqing 已提交
2326 2327 2328

**Example**

2329
```js
W
wusongqing 已提交
2330
async function example() {
A
Annie_wang 已提交
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let getImageOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
    order: fileKeyObj.DATE_ADDED + ' DESC',
  };
  let fetchFileResult = await media.getFileAssets(getImageOp);
  fetchFileResult.getAllObject().then((fileAssetList) => {
    for (let i = 0; i < fetchFileResult.getCount(); i++) {
      console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
    } 
    fetchFileResult.close();
  }).catch((error) => {
    console.error('getAllObject failed with error: ' + error);
  });
W
wusongqing 已提交
2347 2348 2349
}
```

W
wusongqing 已提交
2350
## Album<sup>7+</sup>
W
wusongqing 已提交
2351

A
Annie_wang 已提交
2352
Provides APIs to manage albums.
W
wusongqing 已提交
2353

W
wusongqing 已提交
2354
### Attributes
W
wusongqing 已提交
2355 2356 2357

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

W
wusongqing 已提交
2358 2359
| Name          | Type   | Readable  | Writable  | Description     |
| ------------ | ------ | ---- | ---- | ------- |
W
wusongqing 已提交
2360
| albumId | number | Yes   | No   | Album ID.   |
A
Annie_wang 已提交
2361 2362 2363
| albumName | string | Yes   | Yes   | Name of the album.   |
| albumUri<sup>8+</sup> | string | Yes   | No   | URI of the album.  |
| dateModified | number | Yes   | No   | Date when the album was last modified.   |
W
wusongqing 已提交
2364 2365 2366
| count<sup>8+</sup> | number | Yes   | No   | Number of files in the album.|
| relativePath<sup>8+</sup> | string | Yes   | No   | Relative path of the album.   |
| coverUri<sup>8+</sup> | string | Yes   | No   | URI of the cover file of the album.|
W
wusongqing 已提交
2367 2368 2369 2370 2371

### commitModify<sup>8+</sup>

commitModify(callback: AsyncCallback&lt;void&gt;): void

A
Annie_wang 已提交
2372
Commits the modification on the album attributes to the database.
W
wusongqing 已提交
2373 2374 2375 2376 2377 2378 2379

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2380 2381
| Name  | Type                     | Mandatory| Description      |
| -------- | ------------------------- | ---- | ---------- |
A
Annie_wang 已提交
2382
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback that returns no value.|
W
wusongqing 已提交
2383 2384 2385

**Example**

2386
```js
W
wusongqing 已提交
2387
async function example() {
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1'],
  };
  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
  const album = albumList[0];
  album.albumName = 'hello';
  album.commitModify((error) => {
    if (error) {
      console.error('commitModify failed with error: ' + error);
      return;
    }
    console.info('commitModify successful.');
A
Annie_wang 已提交
2402
  });
W
wusongqing 已提交
2403 2404 2405 2406 2407 2408 2409
}
```

### commitModify<sup>8+</sup>

commitModify(): Promise&lt;void&gt;

A
Annie_wang 已提交
2410
Commits the modification on the album attributes to the database.
W
wusongqing 已提交
2411 2412 2413 2414 2415 2416 2417

**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

W
wusongqing 已提交
2418 2419
| Type                 | Description          |
| ------------------- | ------------ |
A
Annie_wang 已提交
2420
| Promise&lt;void&gt; | Promise that returns no value.|
W
wusongqing 已提交
2421 2422 2423

**Example**

2424
```js
W
wusongqing 已提交
2425
async function example() {
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1'],
  };
  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
  const album = albumList[0];
  album.albumName = 'hello';
  album.commitModify().then(() => {
    console.info('commitModify successfully');
  }).catch((error) => {
    console.error('commitModify failed with error: ' + error);
  });
}
```

### getFileAssets<sup>7+</sup>

getFileAssets(callback: AsyncCallback&lt;FetchFileResult&gt;): void

Obtains the file assets in this album. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

| Name  | Type                                               | Mandatory| Description                               |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
A
Annie_wang 已提交
2456
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback invoked to return the file retrieval result set of the album.|
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479

**Example**

```js
async function example() {
  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1'],
  };
  // Obtain the albums that meet the retrieval options and return the album list.
  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
  const album = albumList[0];
  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
  album.getFileAssets((error, fetchFileResult) => {
    if (error) {
      console.error('album getFileAssets failed with error: ' + error);
      return;
    }
    let count = fetchFileResult.getCount();
    console.info('album getFileAssets successfully, count: ' + count);
    fetchFileResult.close();
  });
W
wusongqing 已提交
2480 2481 2482
}
```

W
wusongqing 已提交
2483
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494

getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void

Obtains the file assets in this album. This API uses an asynchronous callback to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2495 2496 2497
| Name  | Type                                               | Mandatory| Description                               |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
A
Annie_wang 已提交
2498
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback invoked to return the file retrieval result set of the album.|
W
wusongqing 已提交
2499 2500 2501

**Example**

2502
```js
W
wusongqing 已提交
2503
async function example() {
2504 2505 2506 2507 2508 2509 2510 2511
  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1'],
  };
  let fileNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
A
Annie_wang 已提交
2512
  };
2513 2514 2515 2516 2517 2518 2519 2520
  // Obtain the albums that meet the retrieval options and return the album list.
  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
  const album = albumList[0];
  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
  album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
    if (error) {
      console.error('album getFileAssets failed with error: ' + error);
      return;
W
wusongqing 已提交
2521
    }
2522 2523 2524 2525
    let count = fetchFileResult.getCount();
    console.info('album getFileAssets successfully, count: ' + count);
    fetchFileResult.close();
  });
W
wusongqing 已提交
2526 2527 2528
}
```

W
wusongqing 已提交
2529
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540

 getFileAssets(options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;

Obtains the file assets in this album. This API uses a promise to return the result.

**Required permissions**: ohos.permission.READ_MEDIA

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
2541 2542 2543
| Name | Type                                    | Mandatory| Description          |
| ------- | ---------------------------------------- | ---- | -------------- |
| options | [MediaFetchOptions](#mediafetchoptions7) | No  | Options for fetching the files.|
W
wusongqing 已提交
2544 2545 2546

**Return value**

W
wusongqing 已提交
2547 2548
| Type                                         | Description                     |
| --------------------------------------------- | ------------------------- |
A
Annie_wang 已提交
2549
| Promise<[FetchFileResult](#fetchfileresult7)> | Promise used to return the file retrieval result set of the album.|
W
wusongqing 已提交
2550 2551 2552

**Example**

2553
```js
W
wusongqing 已提交
2554
async function example() {
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
  // To obtain the file assets in an album, you must preset the album and resources. The sample code below presets 'New Album 1'.
  let AlbumNoArgsfetchOp = {
    selections: mediaLibrary.FileKey.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1'],
  };
  let fileNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
  };
  // Obtain the albums that meet the retrieval options and return the album list.
  const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
  const album = albumList[0];
  // Obtain an album from the album list and obtain all media assets that meet the retrieval options in the album.
  album.getFileAssets(fileNoArgsfetchOp).then((fetchFileResult) => {
    let count = fetchFileResult.getCount();
    console.info('album getFileAssets successfully, count: ' + count);
    fetchFileResult.close();
  }).catch((error) => {
    console.error('album getFileAssets failed with error: ' + error);
  });
W
wusongqing 已提交
2575 2576 2577 2578 2579
}
```

## PeerInfo<sup>8+</sup>

A
Annie_wang 已提交
2580
Defines information about a registered device.
2581 2582

**System API**: This is a system API.
W
wusongqing 已提交
2583

W
wusongqing 已提交
2584
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
W
wusongqing 已提交
2585

W
wusongqing 已提交
2586 2587 2588 2589 2590 2591
| Name      | Type                      | Readable| Writable| Description            |
| ---------- | -------------------------- | ---- | ---- | ---------------- |
| deviceName | string                     | Yes  | No  | Name of the registered device.  |
| networkId  | string                     | Yes  | No  | Network ID of the registered device.|
| deviceType | [DeviceType](#devicetype8) | Yes  | No  | Type of the registered device.        |
| isOnline   | boolean                    | Yes  | No  | Whether the registered device is online.        |
W
wusongqing 已提交
2592

W
wusongqing 已提交
2593
## MediaType<sup>8+</sup>
W
wusongqing 已提交
2594 2595 2596 2597 2598

Enumerates media types.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2599 2600 2601 2602 2603 2604
| Name |  Value|  Description|
| ----- |  ---- | ---- |
| FILE  |  0 | File.|
| IMAGE |  1 | Image.|
| VIDEO |  2 | Video.|
| AUDIO |  3 | Audio.|
W
wusongqing 已提交
2605

W
wusongqing 已提交
2606
## FileKey<sup>8+</sup>
W
wusongqing 已提交
2607 2608 2609

Enumerates key file information.

G
gloria 已提交
2610 2611 2612
> **NOTE**
> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.

W
wusongqing 已提交
2613 2614
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2615
| Name         | Value             | Description                                                      |
W
wusongqing 已提交
2616
| ------------- | ------------------- | ---------------------------------------------------------- |
G
Gloria 已提交
2617
| ID            | 'file_id'             | File ID.                                                  |
A
Annie_wang 已提交
2618 2619
| RELATIVE_PATH | 'relative_path'       | Relative path of the user directory.                                          |
| DISPLAY_NAME  | 'display_name'        | File name displayed.                                                  |
G
Gloria 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
| PARENT        | 'parent'              | Parent directory ID.                                                  |
| MIME_TYPE     | 'mime_type'           | Extended file attributes, such as image/, video/, and file/*.                                            |
| MEDIA_TYPE    | 'media_type'          | Media type.                                                  |
| SIZE          | 'size'                | File size, in bytes.                                    |
| DATE_ADDED    | 'date_added'          | Date when the file was added. The value is the number of seconds elapsed since the Epoch time.            |
| 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.|
| DATE_TAKEN    | 'date_taken'          | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time.            |
| TITLE         | 'title'               | Title in the file.                                                  |
| ARTIST        | 'artist'              | Artist of the file.                                                      |
| AUDIOALBUM    | 'audio_album'         | Audio album.                                                      |
| DURATION      | 'duration'            | Duration, in ms.                                      |
| WIDTH         | 'width'               | Image width, in pixels.                                    |
| HEIGHT        | 'height'              | Image height, in pixels.                                    |
| ORIENTATION   | 'orientation'         | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
| ALBUM_ID      | 'bucket_id'           | ID of the album to which the file belongs.                                      |
| ALBUM_NAME    | 'bucket_display_name' | Name of the album to which the file belongs.                                        |
W
wusongqing 已提交
2636

W
wusongqing 已提交
2637
## DirectoryType<sup>8+</sup>
W
wusongqing 已提交
2638 2639 2640 2641 2642

Enumerates directory types.

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2643 2644 2645 2646 2647 2648 2649 2650
| Name         | Value|  Description              |
| ------------- | --- | ------------------ |
| DIR_CAMERA    |  0 | Directory of camera files.|
| DIR_VIDEO     |  1 |  Directory of video files.      |
| DIR_IMAGE     |  2 | Directory of image files.      |
| DIR_AUDIO     |  3 | Directory of audio files.      |
| DIR_DOCUMENTS |  4 | Directory of documents.      |
| DIR_DOWNLOAD  |  5 |  Download directory.      |
W
wusongqing 已提交
2651

W
wusongqing 已提交
2652
## DeviceType<sup>8+</sup>
W
wusongqing 已提交
2653

A
Annie_wang 已提交
2654
Enumerates the device types.
2655 2656

**System API**: This is a system API.
W
wusongqing 已提交
2657

W
wusongqing 已提交
2658
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
W
wusongqing 已提交
2659

2660 2661 2662 2663 2664 2665 2666 2667 2668
| Name        |  Value| Description      |
| ------------ | --- | ---------- |
| TYPE_UNKNOWN |  0 | Unknown.|
| TYPE_LAPTOP  |  1 | Laptop.|
| TYPE_PHONE   |  2 | Phone.      |
| TYPE_TABLET  |  3 | Tablet.  |
| TYPE_WATCH   |  4 | Smart watch.  |
| TYPE_CAR     |  5 | Vehicle-mounted device.  |
| TYPE_TV      |  6 | TV.  |
W
wusongqing 已提交
2669

W
wusongqing 已提交
2670
## MediaFetchOptions<sup>7+</sup>
W
wusongqing 已提交
2671

A
Annie_wang 已提交
2672
Defines the options for fetching media files.
W
wusongqing 已提交
2673 2674 2675

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2676 2677
| Name                   | Type               | Readable| Writable| Description                                                        |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
2678 2679
| selections              | string              | Yes  | Yes  | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names when files are fetched. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs           | Array&lt;string&gt; | Yes  | Yes  | Values of the conditions specified in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
G
Gloria 已提交
2680
| 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'|
A
Annie_wang 已提交
2681
| uri<sup>8+</sup>        | string              | Yes  | Yes  | URI of the file.                                                     |
2682 2683
| networkId<sup>8+</sup>  | string              | Yes  | Yes  | Network ID of the registered device.                                              |
| extendArgs<sup>8+</sup> | string              | Yes  | Yes  | Extended parameters for fetching the files. Currently, no extended parameters are available.                        |
W
wusongqing 已提交
2684 2685 2686

## Size<sup>8+</sup>

A
Annie_wang 已提交
2687
Defines the image size.
2688

W
wusongqing 已提交
2689
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
W
wusongqing 已提交
2690

W
wusongqing 已提交
2691 2692 2693 2694
| Name    | Type    | Readable  | Writable  | Description      |
| ------ | ------ | ---- | ---- | -------- |
| width  | number | Yes   | Yes   | Image width, in pixels.|
| height | number | Yes   | Yes   | Image height, in pixels.|
W
wusongqing 已提交
2695

G
Gloria 已提交
2696
## MediaAssetOption
W
wusongqing 已提交
2697

A
Annie_wang 已提交
2698
Defines the media asset option.
W
wusongqing 已提交
2699 2700 2701

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2702 2703 2704 2705
| Name        | Type  | Readable| Writable| Description                                                        |
| ------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| src          | string | Yes  | Yes  | Application sandbox oath of the local file.                                      |
| mimeType     | string | Yes  | Yes  | Multipurpose Internet Mail Extensions (MIME) type of the media.<br>The value can be 'image/\*', 'video/\*', 'audio/\*' or 'file\*'.|
A
Annie_wang 已提交
2706
| relativePath | string | Yes  | Yes  | Custom path of 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 documents: **'Documents/'**|
W
wusongqing 已提交
2707

G
Gloria 已提交
2708
## MediaSelectOption
W
wusongqing 已提交
2709

A
Annie_wang 已提交
2710
Defines media selection option.
W
wusongqing 已提交
2711 2712 2713

**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2714 2715
| Name   | Type    | Readable| Writable| Description                  |
| ----- | ------ | ---- | ---- | -------------------- |
G
gloria 已提交
2716
| type  | 'image' &#124; 'video' &#124; 'media' | Yes   | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
G
Gloria 已提交
2717
| 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.           |