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

W
wusongqing 已提交
3
> **NOTE**
4
> The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
W
wusongqing 已提交
5 6

## Modules to Import
7
```js
W
wusongqing 已提交
8
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
W
wusongqing 已提交
9 10
```

W
wusongqing 已提交
11
## mediaLibrary.getMediaLibrary<sup>8+</sup>
W
wusongqing 已提交
12 13 14

getMediaLibrary(context: Context): MediaLibrary

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

17 18
This API can be used only in the stage model.

W
wusongqing 已提交
19 20 21 22
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Parameters**

W
wusongqing 已提交
23 24 25
| Name | Type   | Mandatory| Description                      |
| ------- | ------- | ---- | -------------------------- |
| context | Context | Yes  | Context of the ability.|
W
wusongqing 已提交
26 27 28

**Return value**

W
wusongqing 已提交
29 30
| Type                           | Description   |
| ----------------------------- | :---- |
W
wusongqing 已提交
31 32
| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.|

W
wusongqing 已提交
33 34
**Example (from API version 9)**

35 36 37
```ts
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
W
wusongqing 已提交
38 39 40
```

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

42
```js
W
wusongqing 已提交
43 44
import featureAbility from '@ohos.ability.featureAbility';

45 46
let context = featureAbility.getContext();
let media = mediaLibrary.getMediaLibrary(context);
W
wusongqing 已提交
47
```
48

W
wusongqing 已提交
49 50 51 52 53 54
## 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.

55 56
This API can be used only in the FA model.

W
wusongqing 已提交
57 58 59 60 61 62 63 64 65 66 67
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

**Return value**

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

**Example**

```js
68
let media = mediaLibrary.getMediaLibrary();
W
wusongqing 已提交
69 70
```

W
wusongqing 已提交
71 72
## MediaLibrary

W
wusongqing 已提交
73
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
74 75 76 77 78 79 80 81 82 83 84 85


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.

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

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

**Parameters**

W
wusongqing 已提交
86 87 88 89
| Name  | Type                                               | Mandatory| Description                             |
| -------- | --------------------------------------------------- | ---- | --------------------------------- |
| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Asynchronous callback of **FetchFileResult**.|
W
wusongqing 已提交
90 91 92

**Example**

93 94 95 96
```js
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
W
wusongqing 已提交
97 98 99
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
};
100 101 102 103
media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
    if (fetchFileResult == undefined) {
        console.error('Failed to get fetchFileResult: ' + error);
        return;
W
wusongqing 已提交
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
    const count = fetchFileResult.getCount();
    if (count < 0) {
        console.error('Failed to get count from fetchFileResult: count: ' + count);
        return;
    }
    if (count == 0) {
        console.info('The count of fetchFileResult is zero');
        return;
    }

    console.info('Get fetchFileResult success, count: ' + count);
    fetchFileResult.getFirstObject((err, fileAsset) => {
        if (fileAsset == undefined) {
            console.error('Failed to get first object: ' + err);
            return;
        }
        console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
        for (let i = 1; i < count; i++) {
            fetchFileResult.getNextObject((err, fileAsset) => {
                if (fileAsset == undefined) {
                    console.error('Failed to get next object: ' + err);
                    return;
                }
                console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
            })
        }
    });
W
wusongqing 已提交
132 133
});
```
W
wusongqing 已提交
134
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
135 136 137 138 139 140 141 142 143 144 145

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

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

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

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

**Parameters**

W
wusongqing 已提交
146 147 148
| Name | Type                                    | Mandatory| Description        |
| ------- | ---------------------------------------- | ---- | ------------ |
| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the files.|
W
wusongqing 已提交
149 150 151

**Return value**

W
wusongqing 已提交
152 153 154
| Type                                | Description          |
| ------------------------------------ | -------------- |
| [FetchFileResult](#fetchfileresult7) | Result set of the file retrieval operation.|
W
wusongqing 已提交
155 156 157

**Example**

158 159 160 161
```js
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
W
wusongqing 已提交
162 163 164
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
};
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
    const count = fetchFileResult.getCount();
    if (count < 0) {
        console.error('Failed to get count from fetchFileResult: count: ' + count);
        return;
    }
    if (count == 0) {
        console.info('The count of fetchFileResult is zero');
        return;
    }
    console.info('Get fetchFileResult success, count: ' + count);
    fetchFileResult.getFirstObject().then(function(fileAsset) {
        console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
        for (let i = 1; i < count; i++) {
            fetchFileResult.getNextObject().then(function(fileAsset) {
                console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName);
            }).catch(function(err) {
                console.error('Failed to get next object: ' + err);
            })
        }
    }).catch(function(err) {
        console.error('Failed to get first object: ' + err);
    });
W
wusongqing 已提交
188
}).catch(function(err){
189
    console.error("Failed to get file assets: " + err);
W
wusongqing 已提交
190 191 192 193 194
});
```

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

G
gloria 已提交
195
on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback: Callback&lt;void&gt;): void
W
wusongqing 已提交
196 197 198 199 200 201 202

Subscribes to the media library changes. This API uses an asynchronous callback to return the result.

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

**Parameters**

W
wusongqing 已提交
203 204
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
205 206
| type     | 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange'               | Yes   | Media type.<br>'deviceChange': registered device change<br>'albumChange': album change<br>'imageChange': image file change<br>'audioChange': audio file change<br>'videoChange': video file change<br>'fileChange': file change<br>'remoteFileChange': file change on the registered device|
| callback | Callback&lt;void&gt; | Yes   | Void callback.                                   |
W
wusongqing 已提交
207 208 209

**Example**

210
```js
W
wusongqing 已提交
211
media.on('imageChange', () => {
W
wusongqing 已提交
212 213 214 215 216
    // image file had changed, do something
})
```
### off<sup>8+</sup>

G
gloria 已提交
217
off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback?: Callback&lt;void&gt;): void
W
wusongqing 已提交
218 219 220 221 222 223 224

Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result.

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

**Parameters**

W
wusongqing 已提交
225 226
| Name     | Type                  | Mandatory  | Description                                      |
| -------- | -------------------- | ---- | ---------------------------------------- |
227 228
| type     | 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange'               | Yes   | Media type.<br>'deviceChange': registered device change<br>'albumChange': album change<br>'imageChange': image file change<br>'audioChange': audio file change<br>'videoChange': video file change<br>'fileChange': file change<br>'remoteFileChange': file change on the registered device|
| callback | Callback&lt;void&gt; | No   | Void callback.                                   |
W
wusongqing 已提交
229 230 231

**Example**

232
```js
W
wusongqing 已提交
233
media.off('imageChange', () => {
W
wusongqing 已提交
234 235 236 237
    // stop listening success
})
```

238
### createAsset<sup>8+</sup>
W
wusongqing 已提交
239 240 241 242 243 244 245 246 247 248 249

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.

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

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

**Parameters**

W
wusongqing 已提交
250 251 252 253 254 255
| Name      | Type                                   | Mandatory| Description                                                        |
| ------------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
| mediaType    | [MediaType](#mediatype8)                | Yes  | Media type.                                                    |
| displayName  | string                                  | Yes  | Display file name.                                                  |
| relativePath | string                                  | Yes  | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.|
| callback     | AsyncCallback<[FileAsset](#fileasset7)> | Yes  | Asynchronous callback for **FileAsset**.                         |
W
wusongqing 已提交
256 257 258

**Example**

259
```js
W
wusongqing 已提交
260 261 262 263 264
async function example() {
    // 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);
W
wusongqing 已提交
265
    media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => {
W
wusongqing 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
        if (fileAsset != undefined) {
            console.info('createAsset successfully, message = ' + err);
        } else {
            console.info('createAsset failed, message = ' + err);
        }
    });
}
```

### 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.

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

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

**Parameters**

W
wusongqing 已提交
287 288 289 290 291
| Name      | Type                    | Mandatory| Description                                                        |
| ------------ | ------------------------ | ---- | ------------------------------------------------------------ |
| mediaType    | [MediaType](#mediatype8) | Yes  | Media type.                                                    |
| displayName  | string                   | Yes  | Display file name.                                                  |
| relativePath | string                   | Yes  | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.|
W
wusongqing 已提交
292 293 294

**Return value**

W
wusongqing 已提交
295 296 297
| Type                    | Description             |
| ------------------------ | ----------------- |
| [FileAsset](#fileasset7) | Media data (FileAsset).|
W
wusongqing 已提交
298 299 300

**Example**

301
```js
302 303 304 305 306 307 308 309 310 311 312
async function example() {
    // 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((err) => {
        console.info('createAsset failed, message = ' + err);
    });
}
W
wusongqing 已提交
313 314
```

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
### 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**
| Type                 | Description                  |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|

**Example**

```js
async function example() {
    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((err) => {
        console.info("deleteAsset failed with error:"+ err);
    });
}
```

### deleteAsset<sup>8+</sup>
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.|
|callback |AsyncCallback\<void>| Yes |Callback used to return the result.|

**Example**

```js
async function example() {
    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, (err) => {
        if (err != undefined) {
            console.info("deleteAsset successfully");
        } else {
            console.info("deleteAsset failed with error:"+ err);
        }
    });
}
```

W
wusongqing 已提交
406 407 408 409 410 411 412 413 414 415
### getPublicDirectory<sup>8+</sup>

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

Obtains a public directory. This API uses an asynchronous callback to return the result.

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

**Parameters**

W
wusongqing 已提交
416 417 418 419
| Name  | Type                            | Mandatory| Description                     |
| -------- | -------------------------------- | ---- | ------------------------- |
| type     | [DirectoryType](#directorytype8) | Yes  | Type of the public directory.             |
| callback | AsyncCallback&lt;string&gt;      | Yes  | Callback used to return the public directory.|
W
wusongqing 已提交
420 421 422

**Example**

423
```js
W
wusongqing 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => {
    if (dicResult == 'Camera/') {
        console.info('mediaLibraryTest : getPublicDirectory passed');
    } else {
        console.info('mediaLibraryTest : getPublicDirectory failed');
    }
});
```

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

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

Obtains a public directory. This API uses a promise to return the result.

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

**Parameters**

W
wusongqing 已提交
444 445 446
| Name| Type                            | Mandatory| Description        |
| ------ | -------------------------------- | ---- | ------------ |
| type   | [DirectoryType](#directorytype8) | Yes  | Type of the public directory.|
W
wusongqing 已提交
447 448 449

**Return value**

W
wusongqing 已提交
450 451 452
| Type            | Description            |
| ---------------- | ---------------- |
| Promise\<string> | Promise used to return the public directory.|
W
wusongqing 已提交
453 454 455

**Example**

456
```js
W
wusongqing 已提交
457 458 459 460 461 462 463 464 465 466 467
async function example() {
    let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
    const dicResult = await media.getPublicDirectory(DIR_CAMERA);
    if (dicResult == 'Camera/') {
        console.info('MediaLibraryTest : getPublicDirectory');
    } else {
        console.info('MediaLibraryTest : getPublicDirectory failed');
    }
}
```

W
wusongqing 已提交
468
### getAlbums<sup>7+</sup>
W
wusongqing 已提交
469 470 471 472 473 474 475 476 477 478 479

getAlbums(options: MediaFetchOptions, callback: AsyncCallback<Array&lt;Album&gt;>): void

Obtains the albums. 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 已提交
480 481 482 483
| Name  | Type                                        | Mandatory| Description                       |
| -------- | -------------------------------------------- | ---- | --------------------------- |
| options  | [MediaFetchOptions](#mediafetchoptions7)     | Yes  | Options for fetching the albums.               |
| callback | AsyncCallback&lt;Array<[Album](#album7)>&gt; | Yes  | Callback used to return the albums.|
W
wusongqing 已提交
484 485 486

**Example**

487
```js
W
wusongqing 已提交
488 489 490 491
let AlbumNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
};
W
wusongqing 已提交
492
media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => {
W
wusongqing 已提交
493 494 495 496 497 498 499 500 501 502
    if (albumList != undefined) {
        const album = albumList[0];
        console.info('album.albumName = ' + album.albumName);
        console.info('album.count = ' + album.count);
     } else {
        console.info('getAlbum fail, message = ' + err);
     }
})
```

W
wusongqing 已提交
503
### getAlbums<sup>7+</sup>
W
wusongqing 已提交
504 505 506 507 508 509 510 511 512 513 514

getAlbums(options: MediaFetchOptions): Promise<Array&lt;Album&gt;>

Obtains the albums. This API uses a promise to return the result.

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

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

**Parameters**

W
wusongqing 已提交
515 516 517
| Name | Type                                    | Mandatory| Description        |
| ------- | ---------------------------------------- | ---- | ------------ |
| options | [MediaFetchOptions](#mediafetchoptions7) | Yes  | Options for fetching the albums.|
W
wusongqing 已提交
518 519 520

**Return value**

W
wusongqing 已提交
521 522 523
| Type                            | Description         |
| -------------------------------- | ------------- |
| Promise<Array<[Album](#album7)>> | Promise used to return the albums.|
W
wusongqing 已提交
524 525 526

**Example**

527
```js
W
wusongqing 已提交
528 529 530 531
let AlbumNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
};
W
wusongqing 已提交
532
media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){
W
wusongqing 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    console.info("getAlbums successfully:"+ JSON.stringify(albumList));
}).catch(function(err){
    console.info("getAlbums failed with error:"+ err);
});
```

### 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 已提交
550 551 552
| Name     | Type                       | Mandatory  | Description        |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the execution result.|
W
wusongqing 已提交
553 554 555

**Example**

556
```js
W
wusongqing 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
media.release((err) => {
    // do something
});
```

### 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 已提交
573 574
| Type                 | Description                  |
| ------------------- | -------------------- |
W
wusongqing 已提交
575 576 577 578
| Promise&lt;void&gt; | Promise used to return the execution result.|

**Example**

579
```js
W
wusongqing 已提交
580 581 582
media.release()
```

W
wusongqing 已提交
583
### storeMediaAsset<sup>(deprecated)</sup>
W
wusongqing 已提交
584 585 586 587 588

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

Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset.

W
wusongqing 已提交
589 590 591
> **NOTE**
>
> This API is deprecated since API version 9.
W
wusongqing 已提交
592 593 594 595 596

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

**Parameters**

W
wusongqing 已提交
597 598 599 600
| Name     | Type                                   | Mandatory  | Description                     |
| -------- | ------------------------------------- | ---- | ----------------------- |
| option   | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.                |
| callback | AsyncCallback&lt;string&gt;           | Yes   | Callback used to return the URI that stores the media asset.|
W
wusongqing 已提交
601 602 603

**Example**

604
```js
W
wusongqing 已提交
605
let option = {
W
wusongqing 已提交
606 607 608
    src : "/data/storage/el2/base/haps/entry/image.png",
    mimeType : "image/*",
    relativePath : "Pictures/"
W
wusongqing 已提交
609 610 611 612 613 614
};
mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => {
    if (err) {
        console.log("An error occurred when storing the media asset.");
        return;
    }
W
wusongqing 已提交
615
    console.log("Media asset stored.");
W
wusongqing 已提交
616 617
    // Obtain the URI that stores the media asset.
});
618
```
W
wusongqing 已提交
619 620


W
wusongqing 已提交
621
### storeMediaAsset<sup>(deprecated)</sup>
W
wusongqing 已提交
622 623 624 625 626

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

Stores a media asset. This API uses a promise to return the URI that stores the media asset.

W
wusongqing 已提交
627 628 629
> **NOTE**
>
> This API is deprecated since API version 9.
W
wusongqing 已提交
630 631 632 633 634

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

**Parameters**

W
wusongqing 已提交
635 636 637
| Name   | Type                                   | Mandatory  | Description     |
| ------ | ------------------------------------- | ---- | ------- |
| option | [MediaAssetOption](#mediaassetoption) | Yes   | Media asset option.|
W
wusongqing 已提交
638 639 640

**Return value**

W
wusongqing 已提交
641 642
| Type                   | Description                          |
| --------------------- | ---------------------------- |
W
wusongqing 已提交
643 644 645 646
| Promise&lt;string&gt; | Promise used to return the URI that stores the media asset.|

**Example**

647
```js
W
wusongqing 已提交
648
let option = {
W
wusongqing 已提交
649 650 651
    src : "/data/storage/el2/base/haps/entry/image.png",
    mimeType : "image/*",
    relativePath : "Pictures/"
W
wusongqing 已提交
652 653 654 655 656 657 658
};
mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
    console.log("Media asset stored.");
    // Obtain the URI that stores the media asset.
}).catch((err) => {
    console.log("An error occurred when storing the media assets.");
});
659
```
W
wusongqing 已提交
660 661


W
wusongqing 已提交
662
### startImagePreview<sup>(deprecated)</sup>
W
wusongqing 已提交
663 664 665

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

666
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 execution result.
W
wusongqing 已提交
667

W
wusongqing 已提交
668 669 670
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\<Image>** component can be used to render and display local and online images.
W
wusongqing 已提交
671 672 673 674 675

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

**Parameters**

W
wusongqing 已提交
676 677
| Name     | Type                       | Mandatory  | Description                                      |
| -------- | ------------------------- | ---- | ---------------------------------------- |
678
| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
W
wusongqing 已提交
679 680
| index    | number                    | Yes   | Index of the first image to preview.                              |
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the image preview result. If the preview fails, an error message is returned.                       |
W
wusongqing 已提交
681 682 683

**Example**

684
```js
W
wusongqing 已提交
685
let images = [
686 687
    "datashare:///media/xxxx/2",
    "datashare:///media/xxxx/3"
W
wusongqing 已提交
688
];
W
wusongqing 已提交
689
/* Preview online images.
W
wusongqing 已提交
690 691 692 693
let images = [
    "https://media.xxxx.com/image1.jpg",
    "https://media.xxxx.com/image2.jpg"
];
W
wusongqing 已提交
694
*/
W
wusongqing 已提交
695 696 697 698 699 700 701 702
let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => {
    if (err) {
        console.log("An error occurred when previewing the images.");
        return;
    }
    console.log("Succeeded in previewing the images.");
});
703
```
W
wusongqing 已提交
704 705


W
wusongqing 已提交
706
### startImagePreview<sup>(deprecated)</sup>
W
wusongqing 已提交
707 708 709

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

710
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 execution result.
W
wusongqing 已提交
711

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

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

**Parameters**

W
wusongqing 已提交
720 721
| Name     | Type                       | Mandatory  | Description                                      |
| -------- | ------------------------- | ---- | ---------------------------------------- |
722
| images   | Array&lt;string&gt;       | Yes   | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
W
wusongqing 已提交
723
| callback | AsyncCallback&lt;void&gt; | Yes   | Callback used to return the image preview result. If the preview fails, an error message is returned.                       |
W
wusongqing 已提交
724 725 726

**Example**

727
```js
W
wusongqing 已提交
728
let images = [
729 730
    "datashare:///media/xxxx/2",
    "datashare:///media/xxxx/3"
W
wusongqing 已提交
731
];
W
wusongqing 已提交
732
/* Preview online images.
W
wusongqing 已提交
733 734 735 736
let images = [
    "https://media.xxxx.com/image1.jpg",
    "https://media.xxxx.com/image2.jpg"
];
W
wusongqing 已提交
737
*/
W
wusongqing 已提交
738 739 740 741 742 743 744
mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => {
    if (err) {
        console.log("An error occurred when previewing the images.");
        return;
    }
    console.log("Succeeded in previewing the images.");
});
745
```
W
wusongqing 已提交
746 747


W
wusongqing 已提交
748
### startImagePreview<sup>(deprecated)</sup>
W
wusongqing 已提交
749 750 751

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

752
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 已提交
753

W
wusongqing 已提交
754 755
> **NOTE**
>
756
> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\<Image>** component can be used to render and display local and online images.
W
wusongqing 已提交
757 758 759 760 761

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

**Parameters**

W
wusongqing 已提交
762 763
| Name   | Type                 | Mandatory  | Description                                      |
| ------ | ------------------- | ---- | ---------------------------------------- |
764
| images | Array&lt;string&gt; | Yes   | URIs of the images to preview. The value can start with either **https://** or **datashare://**.|
W
wusongqing 已提交
765
| index  | number              | No   | Index of the first image to preview. If this parameter is not specified, the default value **0** is used.                     |
W
wusongqing 已提交
766 767 768

**Return value**

W
wusongqing 已提交
769 770
| Type                 | Description                             |
| ------------------- | ------------------------------- |
W
wusongqing 已提交
771 772 773 774
| Promise&lt;void&gt; | Promise used to return the image preview result. If the preview fails, an error message is returned.|

**Example**

775
```js
W
wusongqing 已提交
776
let images = [
777 778
    "datashare:///media/xxxx/2",
    "datashare:///media/xxxx/3"
W
wusongqing 已提交
779
];
W
wusongqing 已提交
780
/* Preview online images.
W
wusongqing 已提交
781 782 783 784
let images = [
    "https://media.xxxx.com/image1.jpg",
    "https://media.xxxx.com/image2.jpg"
];
W
wusongqing 已提交
785
*/
W
wusongqing 已提交
786 787 788 789 790 791
let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
    console.log("Succeeded in previewing the images.");
}).catch((err) => {
    console.log("An error occurred when previewing the images.");
});
792
```
W
wusongqing 已提交
793 794


W
wusongqing 已提交
795
### startMediaSelect<sup>(deprecated)</sup>
W
wusongqing 已提交
796 797 798 799 800

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

Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets.

W
wusongqing 已提交
801 802 803
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
W
wusongqing 已提交
804 805 806 807 808

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

**Parameters**

W
wusongqing 已提交
809 810
| Name     | Type                                      | Mandatory  | Description                                  |
| -------- | ---------------------------------------- | ---- | ------------------------------------ |
811
| option   | [MediaSelectOption](#mediaselectoptiondeprecated)  | Yes   | Media selection option.                             |
812
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes   | Callback used to return the list of URIs (starting with **datashare://**) that store the selected media assets.|
W
wusongqing 已提交
813 814 815

**Example**

816 817
```js
let option : mediaLibrary.MediaSelectOption = {
W
wusongqing 已提交
818
    type : "media",
W
wusongqing 已提交
819 820 821 822 823 824 825 826 827 828
    count : 2
};
mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => {
    if (err) {
        console.log("An error occurred when selecting the media asset.");
        return;
    }
    console.log("Media asset selected.");
    // Obtain the media selection value.
});
829
```
W
wusongqing 已提交
830 831


W
wusongqing 已提交
832
### startMediaSelect<sup>(deprecated)</sup>
W
wusongqing 已提交
833 834 835 836 837

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

Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets.

W
wusongqing 已提交
838 839 840
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos).
W
wusongqing 已提交
841 842 843 844 845

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

**Parameters**

W
wusongqing 已提交
846 847
| Name   | Type                                     | Mandatory  | Description     |
| ------ | --------------------------------------- | ---- | ------- |
848
| option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes   | Media selection option.|
W
wusongqing 已提交
849 850 851

**Return value**

W
wusongqing 已提交
852 853
| Type                                | Description                                      |
| ---------------------------------- | ---------------------------------------- |
854
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the list of URIs (starting with **datashare://**) that store the selected media assets.|
W
wusongqing 已提交
855 856 857

**Example**

858 859
```js
let option : mediaLibrary.MediaSelectOption = {
W
wusongqing 已提交
860
    type : "media",
W
wusongqing 已提交
861 862 863 864 865 866 867 868 869
    count : 2
};
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
    console.log("Media asset selected.");
    // Obtain the media selection value.
}).catch((err) => {
    console.log("An error occurred when selecting the media assets.");
});

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
```
### 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 已提交
887
|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

**Example**

```js
async function example() {
    media.getActivePeers().then((devicesInfo) => {
        if (devicesInfo != undefined) {
            for (let i = 0; i < devicesInfo.length; i++) {
            console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
            }
        } else {
            console.info('get distributed info is undefined!')
        }
    }).catch((err) => {
        console.info("get distributed info failed with error:" + err);
    });
}
```

### 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                  |
| ------------------- | -------------------- |
G
gloria 已提交
923
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

**Example**

```js
async function example() {
    media.getActivePeers((err, devicesInfo) => {
        if (devicesInfo != undefined) {
            for (let i = 0; i < devicesInfo.length; i++) {
                console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
            }
        } else {
            console.info('get distributed fail, message = ' + err)
        }
    })
}
```


### 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 已提交
958
|  Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993

**Example**

```js
async function example() {
    media.getAllPeers().then((devicesInfo) => {
        if (devicesInfo != undefined) {
            for (let i = 0; i < devicesInfo.length; i++) {
                console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
            }
        } else {
            console.info('get distributed info is undefined!')
        }
    }).catch((err) => {
        console.info("get distributed info failed with error:" + err);
    });
}
```

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

getAllPeers(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                  |
| ------------------- | -------------------- |
G
gloria 已提交
994
| callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

**Example**

```js
async function example() {
    media.getAllPeers((err, devicesInfo) => {
        if (devicesInfo != undefined) {
            for (let i = 0; i < devicesInfo.length; i++) {
            console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
            }
        } else {
            console.info('get distributed fail, message = ' + err)
        }
    })
}
```
W
wusongqing 已提交
1011

W
wusongqing 已提交
1012
## FileAsset<sup>7+</sup>
W
wusongqing 已提交
1013 1014 1015

Provides APIs for encapsulating file asset attributes.

G
gloria 已提交
1016 1017 1018 1019 1020
> **NOTE**
> 
> 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 已提交
1021 1022 1023 1024
### Attributes

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

W
wusongqing 已提交
1025
| Name                     | Type                    | Readable| Writable| Description                                                  |
W
wusongqing 已提交
1026
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
W
wusongqing 已提交
1027
| id                        | number                   | Yes  | No  | File asset ID.                                          |
1028
| uri                       | string                   | Yes  | No  | File asset URI, for example, **datashare:///media/image/2**.        |
W
wusongqing 已提交
1029 1030 1031
| mimeType                  | string                   | Yes  | No  | Extended file attributes.                                          |
| mediaType<sup>8+</sup>    | [MediaType](#mediatype8) | Yes  | No  | Media type.                                              |
| displayName               | string                   | Yes  | Yes  | Display file name, including the file name extension.                                |
G
gloria 已提交
1032
| title                     | string                   | Yes  | Yes  | Title in the file. By default, it carries the file name without extension.                                              |
W
wusongqing 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
| relativePath<sup>8+</sup> | string                   | Yes  | Yes  | Relative public directory of the file.                                      |
| parent<sup>8+</sup>       | number                   | Yes  | No  | Parent directory ID.                                              |
| size                      | number                   | Yes  | No  | File size, in bytes.                                |
| 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 was 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.)        |
| 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 已提交
1044
| duration<sup>8+</sup>     | number                   | Yes  | No  | Duration, in ms.                                  |
W
wusongqing 已提交
1045 1046 1047
| albumId                   | number                   | Yes  | No  | ID of the album to which the file belongs.                                  |
| albumUri<sup>8+</sup>     | string                   | Yes  | No  | URI of the album to which the file belongs.                                     |
| albumName                 | string                   | Yes  | No  | Name of the album to which the file belongs.                                    |
W
wusongqing 已提交
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061


### 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 已提交
1062
| Name     | Type                          | Mandatory  | Description                 |
W
wusongqing 已提交
1063
| -------- | ---------------------------- | ---- | ------------------- |
W
wusongqing 已提交
1064
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is a directory.|
W
wusongqing 已提交
1065 1066 1067

**Example**

1068
```js
W
wusongqing 已提交
1069
async function example() {
W
wusongqing 已提交
1070
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.isDirectory((err, isDirectory) => {
        // do something
    });
}
```

### 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 已提交
1098 1099
| Type                    | Description                          |
| ---------------------- | ---------------------------- |
W
wusongqing 已提交
1100 1101 1102 1103
| Promise&lt;boolean&gt; | Promise used to return whether the file asset is a directory.|

**Example**

1104
```js
W
wusongqing 已提交
1105
async function example() {
W
wusongqing 已提交
1106
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.isDirectory().then(function(isDirectory){
        console.info("isDirectory result:"+ isDirectory);
    }).catch(function(err){
        console.info("isDirectory failed with error:"+ err);
    });
}
```

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

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

W
wusongqing 已提交
1128
Commits the modification in this file asset to the database. This API uses an asynchronous callback to return the result.
W
wusongqing 已提交
1129 1130 1131 1132 1133 1134 1135

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

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

**Parameters**

W
wusongqing 已提交
1136 1137 1138
| Name     | Type                       | Mandatory  | Description   |
| -------- | ------------------------- | ---- | ----- |
| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.|
W
wusongqing 已提交
1139 1140 1141

**Example**

1142
```js
W
wusongqing 已提交
1143
async function example() {
W
wusongqing 已提交
1144
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.title = 'newtitle';
    asset.commitModify(() => {
        console.info('commitModify success');   
    });
}
```

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

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

W
wusongqing 已提交
1165
Commits the modification in this file asset to the database. This API uses a promise to return the result.
W
wusongqing 已提交
1166 1167 1168 1169 1170 1171 1172

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

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

**Return value**

W
wusongqing 已提交
1173 1174
| Type                 | Description        |
| ------------------- | ---------- |
W
wusongqing 已提交
1175 1176 1177 1178
| Promise&lt;void&gt; | Void promise.|

**Example**

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

### 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.

W
wusongqing 已提交
1202 1203 1204
> **NOTE**
> 
> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource.
W
wusongqing 已提交
1205

W
wusongqing 已提交
1206
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1207 1208 1209 1210 1211

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

**Parameters**

W
wusongqing 已提交
1212 1213
| Name     | Type                         | Mandatory  | Description                                 |
| -------- | --------------------------- | ---- | ----------------------------------- |
W
wusongqing 已提交
1214
| mode     | string                      | Yes   | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).|
W
wusongqing 已提交
1215
| callback | AsyncCallback&lt;number&gt; | Yes   | Callback used to return the file handle.                           |
W
wusongqing 已提交
1216 1217 1218

**Example**

1219
```js
W
wusongqing 已提交
1220 1221 1222 1223
async function example() {
    let mediaType = mediaLibrary.MediaType.IMAGE;
    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
    const path = await media.getPublicDirectory(DIR_IMAGE);
W
wusongqing 已提交
1224
    const asset = await media.createAsset(mediaType, "image00003.jpg", path);
W
wusongqing 已提交
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    asset.open('rw', (openError, fd) => {
            if(fd > 0){
                asset.close(fd);
            }else{
                console.info('File Open Failed!' + openError);
            }
    });
}
```

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

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

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

1241 1242
>  **NOTE**
>  
W
wusongqing 已提交
1243
> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource.
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                                 |
| ---- | ------ | ---- | ----------------------------------- |
W
wusongqing 已提交
1253
| mode | string | Yes   | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).|
W
wusongqing 已提交
1254 1255 1256

**Return value**

W
wusongqing 已提交
1257 1258
| Type                   | Description           |
| --------------------- | ------------- |
W
wusongqing 已提交
1259 1260 1261 1262
| Promise&lt;number&gt; | Promise used to return the file handle.|

**Example**

1263
```js
W
wusongqing 已提交
1264 1265 1266 1267
async function example() {
    let mediaType = mediaLibrary.MediaType.IMAGE;
    let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
    const path = await media.getPublicDirectory(DIR_IMAGE);
W
wusongqing 已提交
1268
    const asset = await media.createAsset(mediaType, "image00003.jpg", path);
W
wusongqing 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    asset.open('rw')
        .then((fd) => {
            console.info('File fd!' + fd);
        })
        .catch((err) => {
            console.info('File err!' + err);
        });
}
```

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

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

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

W
wusongqing 已提交
1285
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1286 1287 1288 1289 1290

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

**Parameters**

W
wusongqing 已提交
1291 1292 1293 1294
| Name     | Type                       | Mandatory  | Description   |
| -------- | ------------------------- | ---- | ----- |
| fd       | number                    | Yes   | File descriptor.|
| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.|
W
wusongqing 已提交
1295 1296 1297

**Example**

1298
```js
W
wusongqing 已提交
1299
async function example() {
W
wusongqing 已提交
1300
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
W
wusongqing 已提交
1310 1311 1312 1313
    asset.open('rw').then((fd) => {
        console.info('File fd!' + fd);
        asset.close(fd, (closeErr) => {
            if (closeErr != undefined) {
1314
                console.info('mediaLibraryTest : close : FAIL ' + closeErr);
W
wusongqing 已提交
1315 1316 1317 1318 1319 1320 1321 1322
                console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
            } else {
                console.info("=======asset.close success====>");
            }
        });
    })
    .catch((err) => {
        console.info('File err!' + err);
W
wusongqing 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    });
}
```

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

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

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

W
wusongqing 已提交
1333
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
W
wusongqing 已提交
1334 1335 1336 1337 1338

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

**Parameters**

W
wusongqing 已提交
1339 1340 1341
| Name | Type    | Mandatory  | Description   |
| ---- | ------ | ---- | ----- |
| fd   | number | Yes   | File descriptor.|
W
wusongqing 已提交
1342 1343 1344

**Return value**

W
wusongqing 已提交
1345 1346
| Type                 | Description        |
| ------------------- | ---------- |
W
wusongqing 已提交
1347 1348 1349 1350
| Promise&lt;void&gt; | Void promise.|

**Example**

1351
```js
W
wusongqing 已提交
1352
async function example() {
W
wusongqing 已提交
1353
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
W
wusongqing 已提交
1363 1364 1365 1366
    asset.open('rw').then((fd) => {
        console.info('File fd!' + fd);
        asset.close(fd).then((closeErr) => {
            if (closeErr != undefined) {
1367
                console.info('mediaLibraryTest : close : FAIL ' + closeErr);
W
wusongqing 已提交
1368
                console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
W
wusongqing 已提交
1369

W
wusongqing 已提交
1370 1371 1372 1373 1374 1375 1376
            } else {
                console.info("=======asset.close success====>");
            }
        });
    })
    .catch((err) => {
        console.info('File err!' + err);
W
wusongqing 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    });
}
```

### 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 已提交
1393 1394 1395
| Name     | Type                                 | Mandatory  | Description              |
| -------- | ----------------------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback used to return the pixel map of the thumbnail.|
W
wusongqing 已提交
1396 1397 1398

**Example**

1399
```js
W
wusongqing 已提交
1400
async function example() {
W
wusongqing 已提交
1401
    let fileKeyObj = mediaLibrary.FileKey
W
wusongqing 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.getThumbnail((err, pixelmap) => {
1412
        console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
W
wusongqing 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    });
}
```

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

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

Obtains the thumbnail of this file asset, with the thumbnail size passed. 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 已提交
1429 1430 1431 1432
| Name     | Type                                 | Mandatory  | Description              |
| -------- | ----------------------------------- | ---- | ---------------- |
| size     | [Size](#size8)                      | Yes   | Size of the thumbnail.           |
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes   | Callback used to return the pixel map of the thumbnail.|
W
wusongqing 已提交
1433 1434 1435

**Example**

1436
```js
W
wusongqing 已提交
1437
async function example() {
1438
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1439 1440 1441 1442 1443 1444 1445
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
W
wusongqing 已提交
1446
    let size = { width: 720, height: 720 };
W
wusongqing 已提交
1447 1448 1449
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.getThumbnail(size, (err, pixelmap) => {
1450
        console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
W
wusongqing 已提交
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    });
}
```

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

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

Obtains the thumbnail of this file asset, with the thumbnail size passed. This API uses a promise to return the result.

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

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

**Parameters**

W
wusongqing 已提交
1467 1468 1469
| Name | Type            | Mandatory  | Description   |
| ---- | -------------- | ---- | ----- |
| size | [Size](#size8) | No   | Size of the thumbnail.|
W
wusongqing 已提交
1470 1471 1472

**Return value**

W
wusongqing 已提交
1473 1474
| Type                           | Description                   |
| ----------------------------- | --------------------- |
W
wusongqing 已提交
1475 1476 1477 1478
| Promise&lt;image.PixelMap&gt; | Promise to return the pixel map of the thumbnail.|

**Example**

1479
```js
W
wusongqing 已提交
1480
async function example() {
1481
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1482 1483
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
W
wusongqing 已提交
1484 1485 1486 1487
        selections: fileKeyObj.MEDIA_TYPE + '= ?',
        selectionArgs: [imageType.toString()],
        order: fileKeyObj.DATE_ADDED + " DESC",
        extendArgs: "",
W
wusongqing 已提交
1488
    };
W
wusongqing 已提交
1489
    let size = { width: 720, height: 720 };
W
wusongqing 已提交
1490 1491
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
W
wusongqing 已提交
1492 1493
    asset.getThumbnail(size)
    .then((pixelmap) => {
1494
        console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
W
wusongqing 已提交
1495 1496 1497
    })
    .catch((err) => {
        console.info('mediaLibraryTest : getThumbnail fail'+ err);
W
wusongqing 已提交
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
    });
}
```

### 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 已提交
1514 1515 1516 1517
| Name       | Type                       | Mandatory  | Description                                |
| ---------- | ------------------------- | ---- | ---------------------------------- |
| isFavorite | boolean                   | Yes   | Whether to favorite or unfavorite the file. The value **true** means to favorite the file, and **false** means to unfavorite the file.|
| callback   | AsyncCallback&lt;void&gt; | Yes   | Void callback.                             |
W
wusongqing 已提交
1518 1519 1520

**Example**

1521
```js
W
wusongqing 已提交
1522
async function example() {
1523
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.favorite(true,function(err){
        // do something
    });
}
```

### 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 已提交
1551 1552 1553
| Name       | Type     | Mandatory  | Description                                |
| ---------- | ------- | ---- | ---------------------------------- |
| isFavorite | boolean | Yes   | Whether to favorite or unfavorite the file. The value **true** means to favorite the file, and **false** means to unfavorite the file.|
W
wusongqing 已提交
1554 1555 1556

**Return value**

W
wusongqing 已提交
1557 1558
| Type                 | Description        |
| ------------------- | ---------- |
W
wusongqing 已提交
1559 1560 1561 1562
| Promise&lt;void&gt; | Void promise.|

**Example**

1563
```js
W
wusongqing 已提交
1564
async function example() {
1565
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.favorite(true).then(function() {
        console.info("favorite successfully");
    }).catch(function(err){
        console.info("favorite failed with error:"+ err);
    });
}
```

### 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 已提交
1595 1596 1597
| Name     | Type                          | Mandatory  | Description         |
| -------- | ---------------------------- | ---- | ----------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is favorited.|
W
wusongqing 已提交
1598 1599 1600

**Example**

1601
```js
W
wusongqing 已提交
1602
async function example() {
1603
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.isFavorite((err, isFavorite) => {
        if (isFavorite) {
            console.info('FileAsset is favorite');
        }else{
            console.info('FileAsset is not favorite');
        }
    });
}
```

### 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 已提交
1635 1636
| Type                    | Description                |
| ---------------------- | ------------------ |
W
wusongqing 已提交
1637 1638 1639 1640
| Promise&lt;boolean&gt; | Promise used to return whether the file asset is favorited.|

**Example**

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

### 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 已提交
1675 1676 1677 1678
| Name     | Type                       | Mandatory  | Description       |
| -------- | ------------------------- | ---- | --------- |
| isTrash  | boolean                   | Yes   | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes   | Void callback.    |
W
wusongqing 已提交
1679 1680 1681

**Example**

1682
```js
W
wusongqing 已提交
1683
async function example() {
1684
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.trash(true, trashCallBack);
    function trashCallBack(err, trash) {
        console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash');
    }
}
```

### 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 已提交
1715 1716 1717
| Name    | Type     | Mandatory  | Description       |
| ------- | ------- | ---- | --------- |
| isTrash | boolean | Yes   | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.|
W
wusongqing 已提交
1718 1719 1720

**Return value**

W
wusongqing 已提交
1721 1722
| Type                 | Description        |
| ------------------- | ---------- |
W
wusongqing 已提交
1723 1724 1725 1726
| Promise&lt;void&gt; | Void promise.|

**Example**

1727
```js
W
wusongqing 已提交
1728
async function example() {
1729
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
    asset.trash(true).then(function() {
        console.info("trash successfully");
    }).catch(function(err){
        console.info("trash failed with error:"+ err);
    });
}
```

### 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 已提交
1759 1760 1761
| Name     | Type                          | Mandatory  | Description             |
| -------- | ---------------------------- | ---- | --------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes   | Callback used to return whether the file asset is in the trash. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|
W
wusongqing 已提交
1762 1763 1764

**Example**

1765
```js
W
wusongqing 已提交
1766
async function example() {
1767
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1768 1769 1770 1771 1772 1773 1774 1775 1776
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    const fetchFileResult = await media.getFileAssets(getImageOp);
    const asset = await fetchFileResult.getFirstObject();
1777 1778 1779 1780 1781 1782 1783
    asset.isTrash((err, isTrash) => {
      if (isTrash == undefined) {
        console.error('Failed to get trash state: ' + err);
        return;
      }
      console.info('Get trash state success: ' + isTrash);
    });
W
wusongqing 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
}
```

### 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 已提交
1799 1800
| Type                 | Description                  |
| ------------------- | -------------------- |
W
wusongqing 已提交
1801 1802 1803 1804
| Promise&lt;void&gt; | Promise used to return whether the file asset is in the trash. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|

**Example**

1805
```js
W
wusongqing 已提交
1806
async function example() {
1807
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1808 1809 1810 1811 1812 1813 1814 1815 1816
    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(function(isTrash){
1817
      console.info("isTrash result: " + isTrash);
W
wusongqing 已提交
1818
    }).catch(function(err){
1819
      console.error("isTrash failed with error: " + err);
W
wusongqing 已提交
1820 1821 1822 1823
    });
}
```

W
wusongqing 已提交
1824
## FetchFileResult<sup>7+</sup>
W
wusongqing 已提交
1825 1826 1827

Implements the result set of the file retrieval operation.

W
wusongqing 已提交
1828
### getCount<sup>7+</sup>
W
wusongqing 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837

getCount(): number

Obtains the total number of files in the result set.

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

**Return value**

W
wusongqing 已提交
1838 1839
| Type    | Description      |
| ------ | -------- |
W
wusongqing 已提交
1840 1841 1842 1843
| number | Total number of files.|

**Example**

1844
```js
W
wusongqing 已提交
1845
async function example() {
1846
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1847
    let fileType = mediaLibrary.MediaType.FILE;
W
wusongqing 已提交
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
    let getFileCountOneOp = {
        selections: fileKeyObj.MEDIA_TYPE + '= ?',
        selectionArgs: [fileType.toString()],
        order: fileKeyObj.DATE_ADDED + " DESC",
        extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
    const fetchCount = fetchFileResult.getCount();
}
```

W
wusongqing 已提交
1859
### isAfterLast<sup>7+</sup>
W
wusongqing 已提交
1860 1861 1862 1863 1864 1865 1866 1867 1868

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 已提交
1869 1870
| Type     | Description                                |
| ------- | ---------------------------------- |
W
wusongqing 已提交
1871
| boolean | Returns **true** if the cursor is in the last row of the result set; returns *false* otherwise.|
W
wusongqing 已提交
1872 1873 1874

**Example**

1875
```js
W
wusongqing 已提交
1876
async function example() {
1877
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    const fetchCount = fetchFileResult.getCount();
    console.info('mediaLibraryTest : count:' + fetchCount);
    let fileAsset = await fetchFileResult.getFirstObject();
    for (var i = 1; i < fetchCount; i++) {
            fileAsset = await fetchFileResult.getNextObject();
            if(i == fetchCount - 1) {
              console.info('mediaLibraryTest : isLast');
              var result = fetchFileResult.isAfterLast();
              console.info('mediaLibraryTest : isAfterLast:' + result);
              console.info('mediaLibraryTest : isAfterLast end');
              fetchFileResult.close();

            }
    }
}
```

W
wusongqing 已提交
1903
### close<sup>7+</sup>
W
wusongqing 已提交
1904 1905 1906

close(): void

W
wusongqing 已提交
1907
Releases and invalidates this **FetchFileResult** instance. Other APIs in this instance cannot be invoked after it is released.
W
wusongqing 已提交
1908 1909 1910 1911 1912

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

**Example**

1913
```js
W
wusongqing 已提交
1914
async function example() {
1915
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    fetchFileResult.close();
}
```

W
wusongqing 已提交
1928
### getFirstObject<sup>7+</sup>
W
wusongqing 已提交
1929 1930 1931 1932 1933 1934 1935 1936 1937

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 已提交
1938 1939 1940
| Name  | Type                                         | Mandatory| Description                                       |
| -------- | --------------------------------------------- | ---- | ------------------------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the first file asset.|
W
wusongqing 已提交
1941 1942 1943

**Example**

1944
```js
W
wusongqing 已提交
1945
async function example() {
1946
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1947 1948 1949 1950 1951 1952 1953 1954
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
W
wusongqing 已提交
1955
    fetchFileResult.getFirstObject((err, fileAsset) => {
W
wusongqing 已提交
1956 1957 1958 1959
       if (err) {
           console.error('Failed ');
           return;
       }
W
wusongqing 已提交
1960
       console.log('fileAsset.displayName : ' + fileAsset.displayName);
W
wusongqing 已提交
1961 1962 1963 1964
    })
}
```

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

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 已提交
1975 1976 1977
| Type                                   | Description                      |
| --------------------------------------- | -------------------------- |
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the file asset.|
W
wusongqing 已提交
1978 1979 1980

**Example**

1981
```js
W
wusongqing 已提交
1982
async function example() {
1983
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    fetchFileResult.getFirstObject().then(function(fileAsset){
        console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset));
    }).catch(function(err){
        console.info("getFirstObject failed with error:"+ err);
    });
}
```

W
wusongqing 已提交
2000
### getNextObject<sup>7+</sup>
W
wusongqing 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009

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

Obtains the next 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 已提交
2010 2011
| Name   | Type                                         | Mandatory| Description                                     |
| --------- | --------------------------------------------- | ---- | ----------------------------------------- |
2012
| callback| AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the next file asset.|
W
wusongqing 已提交
2013 2014 2015

**Example**

2016
```js
W
wusongqing 已提交
2017
async function example() {
2018
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2019 2020 2021 2022 2023 2024 2025 2026
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
W
wusongqing 已提交
2027
    fetchFileResult.getNextObject((err, fileAsset) => {
W
wusongqing 已提交
2028 2029 2030 2031
       if (err) {
           console.error('Failed ');
           return;
       }
W
wusongqing 已提交
2032
       console.log('fileAsset.displayName : ' + fileAsset.displayName);
W
wusongqing 已提交
2033 2034 2035 2036
    })
}
```

W
wusongqing 已提交
2037
### getNextObject<sup>7+</sup>
W
wusongqing 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046

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

Obtains the next 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 已提交
2047 2048 2049
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
W
wusongqing 已提交
2050 2051 2052

**Example**

2053
```js
W
wusongqing 已提交
2054
async function example() {
2055
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    const fetchCount = fetchFileResult.getCount();
    console.info('mediaLibraryTest : count:' + fetchCount);
W
wusongqing 已提交
2066
    let fileAsset = await fetchFileResult.getNextObject();
W
wusongqing 已提交
2067 2068 2069
}
```

W
wusongqing 已提交
2070
### getLastObject<sup>7+</sup>
W
wusongqing 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079

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 已提交
2080 2081 2082
| Name  | Type                                         | Mandatory| Description                       |
| -------- | --------------------------------------------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes  | Callback used to return the last file asset.|
W
wusongqing 已提交
2083 2084 2085

**Example**

2086
```js
W
wusongqing 已提交
2087
async function example() {
2088
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2089 2090 2091 2092 2093 2094 2095 2096
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
W
wusongqing 已提交
2097
    fetchFileResult.getLastObject((err, fileAsset) => {
W
wusongqing 已提交
2098 2099 2100 2101
       if (err) {
           console.error('Failed ');
           return;
       }
W
wusongqing 已提交
2102
       console.log('fileAsset.displayName : ' + fileAsset.displayName);
W
wusongqing 已提交
2103 2104 2105 2106
    })
}
```

W
wusongqing 已提交
2107
### getLastObject<sup>7+</sup>
W
wusongqing 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116

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 已提交
2117 2118 2119
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
W
wusongqing 已提交
2120 2121 2122

**Example**

2123
```js
W
wusongqing 已提交
2124
async function example() {
2125
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    let lastObject = await fetchFileResult.getLastObject();
}
```

W
wusongqing 已提交
2138
### getPositionObject<sup>7+</sup>
W
wusongqing 已提交
2139 2140 2141 2142 2143 2144 2145 2146 2147

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 已提交
2148 2149 2150
| Name      | Type                                      | Mandatory  | Description                |
| -------- | ---------------------------------------- | ---- | ------------------ |
| index    | number                                   | Yes   | Index of the file asset to obtain. The value starts from **0**.    |
W
wusongqing 已提交
2151
| callback | AsyncCallback&lt;[FileAsset](#fileasset7)&gt; | Yes   | Callback used to return the last file asset.|
W
wusongqing 已提交
2152 2153 2154

**Example**

2155
```js
W
wusongqing 已提交
2156
async function example() {
2157
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2158 2159 2160 2161 2162 2163 2164 2165
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
W
wusongqing 已提交
2166
    fetchFileResult.getPositionObject(0, (err, fileAsset) => {
W
wusongqing 已提交
2167 2168 2169 2170
       if (err) {
           console.error('Failed ');
           return;
       }
W
wusongqing 已提交
2171
       console.log('fileAsset.displayName : ' + fileAsset.displayName);
W
wusongqing 已提交
2172 2173 2174 2175
    })
}
```

W
wusongqing 已提交
2176
### getPositionObject<sup>7+</sup>
W
wusongqing 已提交
2177 2178 2179 2180 2181 2182 2183 2184 2185

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 已提交
2186 2187 2188
| Name   | Type    | Mandatory  | Description            |
| ----- | ------ | ---- | -------------- |
| index | number | Yes   | Index of the file asset to obtain. The value starts from **0**.|
W
wusongqing 已提交
2189 2190 2191

**Return value**

W
wusongqing 已提交
2192 2193 2194
| Type                                   | Description             |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset7)&gt; | Promise used to return the next file asset.|
W
wusongqing 已提交
2195 2196 2197

**Example**

2198
```js
W
wusongqing 已提交
2199
async function example() {
2200
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2201 2202 2203 2204 2205 2206 2207 2208
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
2209
    fetchFileResult.getPositionObject(1) .then(function (fileAsset){
2210
        console.log('fileAsset.displayName : ' + fileAsset.displayName);
2211
    }).catch(function (err) {
2212
        console.info("getFileAssets failed with error:" + err);
2213
    });
W
wusongqing 已提交
2214 2215 2216
}
```

W
wusongqing 已提交
2217
### getAllObject<sup>7+</sup>
W
wusongqing 已提交
2218 2219 2220 2221 2222 2223 2224 2225 2226

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 已提交
2227 2228
| Name      | Type                                      | Mandatory  | Description                  |
| -------- | ---------------------------------------- | ---- | -------------------- |
W
wusongqing 已提交
2229
| callback | AsyncCallback<Array<[FileAsset](#fileasset7)>> | Yes   | Callback used to return the file assets.|
W
wusongqing 已提交
2230 2231 2232

**Example**

2233
```js
W
wusongqing 已提交
2234
async function example() {
2235
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2236 2237 2238 2239 2240 2241 2242 2243
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
W
wusongqing 已提交
2244
    fetchFileResult.getAllObject((err, fileAsset) => {
2245
        if (err) {
W
wusongqing 已提交
2246 2247
           console.error('Failed ');
           return;
2248 2249 2250 2251
        }
        for (let i = 0; i < fetchFileResult.getCount(); i++) {
            console.log('fileAsset.displayName : ' + fileAsset[i].displayName);
        } 
W
wusongqing 已提交
2252 2253 2254 2255
    })
}
```

W
wusongqing 已提交
2256
### getAllObject<sup>7+</sup>
W
wusongqing 已提交
2257 2258 2259 2260 2261 2262 2263 2264 2265

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 已提交
2266 2267 2268
| Type                                    | Description                 |
| ---------------------------------------- | --------------------- |
| Promise<Array<[FileAsset](#fileasset7)>> | Promise used to return the file assets.|
W
wusongqing 已提交
2269 2270 2271

**Example**

2272
```js
W
wusongqing 已提交
2273
async function example() {
2274
    let fileKeyObj = mediaLibrary.FileKey;
W
wusongqing 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
    let imageType = mediaLibrary.MediaType.IMAGE;
    let getImageOp = {
      selections: fileKeyObj.MEDIA_TYPE + '= ?',
      selectionArgs: [imageType.toString()],
      order: fileKeyObj.DATE_ADDED + " DESC",
      extendArgs: "",
    };
    let fetchFileResult = await media.getFileAssets(getImageOp);
    var data = fetchFileResult.getAllObject();
}
```

W
wusongqing 已提交
2287
## Album<sup>7+</sup>
W
wusongqing 已提交
2288 2289 2290

Provides APIs to implement a physical album.

W
wusongqing 已提交
2291
### Attributes
W
wusongqing 已提交
2292 2293 2294

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

W
wusongqing 已提交
2295 2296
| Name          | Type   | Readable  | Writable  | Description     |
| ------------ | ------ | ---- | ---- | ------- |
W
wusongqing 已提交
2297 2298 2299
| albumId | number | Yes   | No   | Album ID.   |
| albumName | string | Yes   | Yes   | Album name.   |
| albumUri<sup>8+</sup> | string | Yes   | No   | Album URI.  |
W
wusongqing 已提交
2300
| dateModified | number | Yes   | No   | Date when the album was modified.   |
W
wusongqing 已提交
2301 2302 2303
| 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 已提交
2304 2305 2306 2307 2308

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

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

W
wusongqing 已提交
2309
Commits the modification in the album attributes to the database. This API uses an asynchronous callback to return the result.
W
wusongqing 已提交
2310 2311 2312 2313 2314 2315 2316

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

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

**Parameters**

W
wusongqing 已提交
2317 2318 2319
| Name  | Type                     | Mandatory| Description      |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | Yes  | Void callback.|
W
wusongqing 已提交
2320 2321 2322

**Example**

2323
```js
W
wusongqing 已提交
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
async function example() {
    let AlbumNoArgsfetchOp = {
        selections: '',
        selectionArgs: [],
    };
    const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
    const album = albumList[0];
    album.albumName = 'hello';
    album.commitModify((err) => {
       if (err) {
           console.error('Failed ');
           return;
       }
       console.log('Modify successful.');
    })
}
```

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

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

W
wusongqing 已提交
2346
Commits the modification in the album attributes to the database. This API uses a promise to return the result.
W
wusongqing 已提交
2347 2348 2349 2350 2351 2352 2353

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

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

**Return value**

W
wusongqing 已提交
2354 2355
| Type                 | Description          |
| ------------------- | ------------ |
W
wusongqing 已提交
2356 2357 2358 2359
| Promise&lt;void&gt; | Void promise.|

**Example**

2360
```js
W
wusongqing 已提交
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
async function example() {
    let AlbumNoArgsfetchOp = {
        selections: '',
        selectionArgs: [],
    };
    const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
    const album = albumList[0];
    album.albumName = 'hello';
    album.commitModify().then(function() {
        console.info("commitModify successfully");
    }).catch(function(err){
        console.info("commitModify failed with error:"+ err);
    });
}
```

W
wusongqing 已提交
2377
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388

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 已提交
2389 2390 2391 2392
| Name  | Type                                               | Mandatory| Description                               |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| options  | [MediaFetchOptions](#mediafetchoptions7)            | Yes  | Options for fetching the files.                     |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes  | Callback used to return the file assets.|
W
wusongqing 已提交
2393 2394 2395

**Example**

2396
```js
W
wusongqing 已提交
2397 2398 2399 2400 2401
async function example() {
    let AlbumNoArgsfetchOp = {
        selections: '',
        selectionArgs: [],
    };
W
wusongqing 已提交
2402 2403 2404 2405
    let fileNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
    }
W
wusongqing 已提交
2406 2407 2408 2409 2410 2411 2412 2413 2414
    const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
    const album = albumList[0];
    album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack);
    function getFileAssetsCallBack(err, fetchFileResult) {
        // do something
    }
}
```

W
wusongqing 已提交
2415
### getFileAssets<sup>7+</sup>
W
wusongqing 已提交
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426

 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 已提交
2427 2428 2429
| Name | Type                                    | Mandatory| Description          |
| ------- | ---------------------------------------- | ---- | -------------- |
| options | [MediaFetchOptions](#mediafetchoptions7) | No  | Options for fetching the files.|
W
wusongqing 已提交
2430 2431 2432

**Return value**

W
wusongqing 已提交
2433 2434 2435
| Type                                         | Description                     |
| --------------------------------------------- | ------------------------- |
| Promise<[FetchFileResult](#fetchfileresult7)> | Promise used to return the file assets.|
W
wusongqing 已提交
2436 2437 2438

**Example**

2439
```js
W
wusongqing 已提交
2440 2441 2442 2443 2444
async function example() {
    let AlbumNoArgsfetchOp = {
        selections: '',
        selectionArgs: [],
    };
W
wusongqing 已提交
2445 2446 2447
    let fileNoArgsfetchOp = {
    selections: '',
    selectionArgs: [],
2448
    };
W
wusongqing 已提交
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461
    const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
    const album = albumList[0];
    album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){
        console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult));
    }).catch(function(err){
        console.info("getFileAssets failed with error:"+ err);
    });
}
```

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

Describes information about a registered device.
2462 2463

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

W
wusongqing 已提交
2465
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
W
wusongqing 已提交
2466

W
wusongqing 已提交
2467 2468 2469 2470 2471 2472
| 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 已提交
2473 2474 2475



W
wusongqing 已提交
2476
## MediaType<sup>8+</sup>
W
wusongqing 已提交
2477 2478 2479 2480 2481

Enumerates media types.

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

2482 2483 2484 2485 2486 2487
| Name |  Value|  Description|
| ----- |  ---- | ---- |
| FILE  |  0 | File.|
| IMAGE |  1 | Image.|
| VIDEO |  2 | Video.|
| AUDIO |  3 | Audio.|
W
wusongqing 已提交
2488

W
wusongqing 已提交
2489
## FileKey<sup>8+</sup>
W
wusongqing 已提交
2490 2491 2492

Enumerates key file information.

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

W
wusongqing 已提交
2497 2498
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core

2499
| Name         | Value             | Description                                                      |
W
wusongqing 已提交
2500
| ------------- | ------------------- | ---------------------------------------------------------- |
G
gloria 已提交
2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
| ID            | "file_id"             | File ID.                                                  |
| RELATIVE_PATH | "relative_path"       | Relative public directory of the file.                                          |
| DISPLAY_NAME  | "display_name"        | Display file name.                                                  |
| PARENT        | "parent"              | Parent directory ID.                                                  |
| MIME_TYPE     | "mime_type"           | Extended file attributes.                                              |
| 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 was 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 已提交
2520

W
wusongqing 已提交
2521
## DirectoryType<sup>8+</sup>
W
wusongqing 已提交
2522 2523 2524 2525 2526

Enumerates directory types.

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

2527 2528 2529 2530 2531 2532 2533 2534
| 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 已提交
2535

W
wusongqing 已提交
2536
## DeviceType<sup>8+</sup>
W
wusongqing 已提交
2537 2538

Enumerates device types.
2539 2540

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

W
wusongqing 已提交
2542
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
W
wusongqing 已提交
2543

2544 2545 2546 2547 2548 2549 2550 2551 2552
| 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 已提交
2553

W
wusongqing 已提交
2554
## MediaFetchOptions<sup>7+</sup>
W
wusongqing 已提交
2555 2556 2557 2558 2559

Describes options for fetching media files.

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

2560 2561 2562 2563 2564 2565 2566 2567
| Name                   | Type               | Readable| Writable| Description                                                        |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
| selections              | string              | Yes  | Yes  | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs           | Array&lt;string&gt; | Yes  | Yes  | Value of the condition, which corresponds to the value of the condition column in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
| 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"|
| uri<sup>8+</sup>        | string              | Yes  | Yes  | File URI.                                                     |
| 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 已提交
2568 2569 2570 2571

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

Describes the image size.
2572

W
wusongqing 已提交
2573
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
W
wusongqing 已提交
2574

W
wusongqing 已提交
2575 2576 2577 2578
| Name    | Type    | Readable  | Writable  | Description      |
| ------ | ------ | ---- | ---- | -------- |
| width  | number | Yes   | Yes   | Image width, in pixels.|
| height | number | Yes   | Yes   | Image height, in pixels.|
W
wusongqing 已提交
2579

W
wusongqing 已提交
2580
## MediaAssetOption<sup>(deprecated)</sup>
W
wusongqing 已提交
2581 2582 2583

Implements the media asset option.

W
wusongqing 已提交
2584
> This API is deprecated since API version 9.
W
wusongqing 已提交
2585 2586 2587 2588

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


2589 2590 2591 2592 2593
| 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\*'.|
| relativePath | string | Yes  | Yes  | Custom path for storing media assets, for example, 'Pictures/'. If this parameter is unspecified, media assets are stored in the default path.<br> Default path of images: 'Pictures/'<br> Default path of videos: 'Videos/'<br> Default path of audios: 'Audios/'<br> Default path of files: 'Documents/'|
W
wusongqing 已提交
2594

W
wusongqing 已提交
2595
## MediaSelectOption<sup>(deprecated)</sup>
W
wusongqing 已提交
2596 2597 2598

Describes media selection option.

W
wusongqing 已提交
2599 2600 2601
> **NOTE**
>
> This API is deprecated since API version 9.
W
wusongqing 已提交
2602 2603 2604

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

2605 2606
| Name   | Type    | Readable| Writable| Description                  |
| ----- | ------ | ---- | ---- | -------------------- |
G
gloria 已提交
2607
| type  | 'image' &#124; 'video' &#124; 'media' | Yes   | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
2608
| count | number | Yes   | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected.           |