未验证 提交 f6fcd07a 编写于 作者: O openharmony_ci 提交者: Gitee

!13325 [翻译完成】I62WZ5

Merge pull request !13325 from Annie_wang/PR11757A
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
- [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) - [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md)
- [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md) - [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md)
- [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) - [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md)
- [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) - [@ohos.application.DataShareExtensionAbility](js-apis-application-dataShareExtensionAbility.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- Stage Model (To Be Deprecated Soon) - Stage Model (To Be Deprecated Soon)
- [@ohos.application.Ability](js-apis-application-ability.md) - [@ohos.application.Ability](js-apis-application-ability.md)
...@@ -212,7 +212,7 @@ ...@@ -212,7 +212,7 @@
- [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md)
- [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userFileManager](js-apis-userfilemanager.md) - [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md) - [@ohos.statfs](js-apis-statfs.md)
......
# User Data Management # @ohos.filemanagement.userFileManager
> **NOTE**<br/> The **userFileManager** module provides user data management capabilities, including accessing and modifying user media data (audio and video clips, images, and files).
> This module is supported since API Version 9. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
```js ```ts
import userFileManager from '@ohos.filemanagement.userfile_manager'; import userFileManager from '@ohos.filemanagement.userFileManager';
``` ```
## userFileManager.getUserFileMgr ## userFileManager.getUserFileMgr
getUserFileMgr(context: Context): UserFileManager getUserFileMgr(context: Context): UserFileManager
Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video files, images, and documents). Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video clips, images, and files).
**Model restriction**: This API can be used only in the stage model. **Model restriction**: This API can be used only in the stage model.
...@@ -23,7 +27,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and ...@@ -23,7 +27,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------- | ---- | -------------------------- | | ------- | ------- | ---- | -------------------------- |
| context | [Context](../apis/js-apis-inner-app-context.md) | Yes | Context of the ability instance.| | context | [Context](js-apis-inner-app-context.md) | Yes | Context of the ability instance.|
**Return value** **Return value**
...@@ -35,652 +39,703 @@ Obtains a **UserFileManager** instance. This instance can be used to access and ...@@ -35,652 +39,703 @@ Obtains a **UserFileManager** instance. This instance can be used to access and
```ts ```ts
const context = getContext(this); const context = getContext(this);
let userFileMgr = userfilemanager.getUserFileMgr(context); let mgr = userFileManager.getUserFileMgr(context);
``` ```
## userFileManager.getUserFileMgr ## UserFileManager
getUserFileMgr(): UserFileManager
Obtains a **UserFileManager** instance.This instance can be used to access and modify user media data (such as audio and video clips, images, and documents).
**Model restriction**: This API can be used only in the FA model.
> **NOTE**<br>You are advised to use [UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr), the API used in the stage model.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Return value**
| Type | Description |
| ----------------------------- | :--------- |
| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.|
**Example** ### getPhotoAssets
```js getPhotoAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
let userFileMgr = userfilemanager.getUserFileMgr();
```
## UserFileManager
### getPublicDirectory Obtains image and video assets. This API uses an asynchronous callback to return the result.
getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string>): void;
Obtains the preset public directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------- | | -------- | ------------------------ | ---- | ------------------------- |
| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | | options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. |
| callback | AsyncCallback&lt;string> | Yes | Callback invoked to return the public directory.| | callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Yes | Callback invoked to return the image and video assets obtained.|
**Example** **Example**
```ts ```ts
async function getPublicDirectoryDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('getPublicDirectoryDemo');
let DIR_CAMERA = directoryType.DIR_CAMERA; async function example() {
console.info('DIR_CAMERA', DIR_CAMERA); console.info('getPhotoAssets');
userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { let predicates = new dataSharePredicates.DataSharePredicates();
if (dicResult == 'Camera/') { let fetchOptions = {
console.info('mediaLibraryTest : getPublicDirectory passed'); fetchColumns: [],
predicates: predicates
};
mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => {
if (fetchResult != undefined) {
console.info('fetchResult success');
let fileAsset = await fetchResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
}
} else { } else {
console.info('mediaLibraryTest : getPublicDirectory failed'); console.info('fetchResult fail' + err);
} }
}); });
} }
``` ```
### getPublicDirectory
getPublicDirectory(type: DirectoryType): Promise&lt;string>; ### getPhotoAssets
getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
Obtains the preset public directory. This API uses a promise to return the result. Obtains image and video assets. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | ------------- | ---- | ------------ | | ------- | ------------------- | ---- | ---------------- |
| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| | options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------- | ---------------- | | --------------------------- | -------------- |
| Promise\<string> | Promise used to return the public directory.| | Promise&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Promise used to return the image and video assets obtained.|
**Example** **Example**
```ts ```ts
async function getPublicDirectoryDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('getPublicDirectoryDemo');
let DIR_CAMERA = directoryType.DIR_CAMERA; async function example() {
console.info('getPhotoAssets');
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOptions = {
fetchColumns: [],
predicates: predicates
};
try { try {
let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); var fetchResult = await mgr.getPhotoAssets(fetchOptions);
console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); if (fetchResult != undefined) {
console.info('fetchResult success');
let fileAsset = await fetchResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
}
}
} catch (err) { } catch (err) {
console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); console.info('getPhotoAssets failed, message = ', err);
} }
} }
``` ```
### createPhotoAsset
### getFileAssets createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback&lt;FileAsset&gt;): void;
getFileAssets(type: Array&lt;MediaType>, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult>): void;
Obtains file assets. This API uses an asynchronous callback to return the result. Creates an image or video asset. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------- | | -------- | ------------------------ | ---- | ------------------------- |
| type | Array&lt;[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | | displayName | string | Yes | File name of the image or video to create. |
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | | albumUri | string | Yes | URI of the album where the image or video is located. |
| callback | AsyncCallback&lt;string> | Yes | Callback invoked to return the file assets obtained.| | callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the image or video created.|
**Example** **Example**
```ts ```ts
async function getFileAssetsDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('getFileAssets');
let fileKeyObj = userfile_manager.FileKey async function example() {
let imageType = userfile_manager.MediaType.IMAGE console.info('createPhotoAssetDemo');
let fetchOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: '', let fetchOptions = {
selectionArgs: [], predicates: predicates
}; };
let albums = await mgr.getPhotoAlbums(fetchOptions);
let album = await albums.getFirstObject();
let testFileName = "testFile" + Date.now() + ".jpg";
mgr.createPhotoAsset(testFileName, album.albumUri, (err, fileAsset) => {
if (fileAsset != undefined) {
console.info('createPhotoAsset file displayName' + fileAsset.displayName);
console.info('createPhotoAsset successfully');
} else {
console.info('createPhotoAsset failed, message = ', err);
}
});
}
```
userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { ### createPhotoAsset
if (fetchFileResult != undefined) {
console.info('fetchFileResult success'); createPhotoAsset(displayName: string, callback: AsyncCallback&lt;FileAsset&gt;): void;
let fileAsset = await fetchFileResult.getFirstObject();
Creates an image or video asset. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------ | ---- | ------------------------- |
| displayName | string | Yes | File name of the image or video to create. |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the image or video created.|
**Example**
```ts
async function example() {
console.info('createPhotoAssetDemo');
let testFileName = "testFile" + Date.now() + ".jpg";
mgr.createPhotoAsset(testFileName, (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName); console.info('createPhotoAsset file displayName' + fileAsset.displayName);
}; console.info('createPhotoAsset successfully');
} else {
console.info('createPhotoAsset failed, message = ', err);
} }
}) });
} }
``` ```
### getFileAssets ### createPhotoAsset
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions): Promise&lt;FetchFileResult>; createPhotoAsset(displayName: string, albumUri?: string): Promise&lt;FileAsset&gt;;
Obtains file assets. This API uses a promise to return the result. Creates an image or video asset. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ---------------- | | -------- | ------------------------ | ---- | ------------------------- |
| type | Array&lt;[MediaType](#mediatype)> | Yes | Type of the media type to obtain.| | displayName | string | Yes | File name of the image or video to create. |
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | | albumUri | string | No | URI of the album where the image or video is located. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------- | -------------- | | --------------------------- | -------------- |
| Promise&lt;[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| | Promise&lt;[FileAsset](#fileasset)&gt; | Promise used to return the image or video created.|
**Example** **Example**
```ts ```ts
async function getFileAssetsDemoPromise() { async function example() {
console.info('getFileAssets'); console.info('createPhotoAssetDemo');
let fileKeyObj = userfile_manager.FileKey
let imageType = userfile_manager.MediaType.IMAGE
let fetchOp = {
selections: '',
selectionArgs: [],
};
try { try {
var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) let testFileName = "testFile" + Date.now() + ".jpg";
let fileAsset = await mgr.createPhotoAsset(testFileName);
console.info('createPhotoAsset file displayName' + fileAsset.displayName);
console.info('createPhotoAsset successfully');
} catch (err) { } catch (err) {
console.info('getFileAssets failed, message = ', err); console.info('createPhotoAsset failed, message = ', err);
}
if (fetchFileResult != undefined) {
console.info('fetchFileResult success');
let fileAsset = await fetchFileResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
};
} }
} }
``` ```
### on ### getPhotoAlbums
on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback&lt;void&gt;): void getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback&lt;FetchResult&lt;Album&gt;&gt;): void;
Subscribes to changes of the file management library. This API uses a callback to return the result.
Obtains image and video albums. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------ | ---- | ------------------------- |
| type | string | Yes | Media type to subscribe to.<br>**deviceChange** indicates the device change.<br>**albumChange** indicates the album change.<br>**imageChange** indicates the image change.<br>**audioChange** indicates the audio file change.<br>**videoChange** indicates the video file change.<br>**fileChange** indicates the file change.<br>**remoteFileChange** indicates the file change on the registered device.| | options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. |
| callback | Callback&lt;void&gt; | Yes | Callback that returns no value. | | callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[Album](#album)&gt;&gt; | Yes | Callback invoked to return the albums obtained.|
**Example** **Example**
```ts ```ts
async function onDemo() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('onDemo')
userFileMgr.on('imageChange', () => { async function example() {
// Image file changes. Do something. console.info('getPhotoAlbumsDemo');
let predicates = new dataSharePredicates.DataSharePredicates();
let albumFetchOptions = {
predicates: predicates
};
mgr.getPhotoAlbums(albumFetchOptions, (err, fetchResult) => {
if (fetchResult != undefined) {
console.info('albums.count = ' + fetchResult.getCount());
fetchResult.getFirstObject((err, album) => {
if (album != undefined) {
console.info('first album.albumName = ' + album.albumName);
} else {
console.info('album is undefined, err = ', err);
}
});
} else {
console.info('getPhotoAlbums fail, message = ', err);
}
}); });
} }
``` ```
### off ### getPhotoAlbums
off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback&lt;void&gt;): void getPhotoAlbums(options: AlbumFetchOptions): Promise&lt;FetchResult&lt;Album&gt;&gt;;
Unsubscribes from changes of the file management library. This API uses a callback to return the result. Obtains image and video albums. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------ | ---- | ------------------------- |
| type | string | Yes | Media type to unsubscribe from.<br>**deviceChange** indicates the device change.<br>**albumChange** indicates the album change.<br>**imageChange** indicates the image change.<br>**audioChange** indicates the audio file change.<br>**videoChange** indicates the video file change.<br>**fileChange** indicates the file change.<br>**remoteFileChange** indicates the file change on the registered device.| | options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. |
| callback | Callback&lt;void&gt; | No | Callback that returns no value. |
**Return value**
| Type | Description |
| --------------------------- | -------------- |
| Promise&lt;[FetchResult](#fetchresult)&lt;[Album](#album)&gt;&gt; | Promise used to return the albums obtained.|
**Example** **Example**
```ts ```ts
async function offDemo() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('offDemo')
userFileMgr.off('imageChange', () => { async function example() {
// stop listening success console.info('getPhotoAlbumsDemo');
}); let predicates = new dataSharePredicates.DataSharePredicates();
let albumFetchOptions = {
predicates: predicates
};
try {
let fetchResult = await mgr.getPhotoAlbums(albumFetchOptions);
console.info('album.count = ' + fetchResult.getCount());
const album = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + album.albumName);
} catch (err) {
console.info('getPhotoAlbums fail, message = ' + err);
}
} }
``` ```
### createAsset ### getPrivateAlbum
createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback&lt;FetchResult&lt;PrivateAlbum&gt;&gt;): void;
Creates a file asset. This API uses an asynchronous callback to return the result.
This is a system API. Obtains the system album. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------ | ---- | ------------------------- |
| mediaType | [MediaType](#mediatype) | Yes | Media type. | | type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. |
| displayName | string | Yes | File name to display. | | callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[PrivateAlbum](#privatealbum)&gt;&gt; | Yes | Callback invoked to return the album obtained.|
| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.|
| callback | AsyncCallback&lt;[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset created. |
**Example** **Example**
```ts ```ts
async function createAssetDemoCallback() { async function example() {
console.info('createAssetDemo') console.info('getPrivateAlbumDemo');
let mediaType = userfile_manager.MediaType.FILE; mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => {
let DIR_DOC = directoryType.DIR_DOCUMENTS; if (fetchResult != undefined) {
const path = await userFileMgr.getPublicDirectory(DIR_DOC); let trashAlbum = await fetchResult.getFirstObject();
userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { console.info('first album.albumName = ' + trashAlbum.albumName);
if (err == undefined) {
console.info('createAsset successfully');
} else { } else {
console.info('createAsset failed, message = ', err); console.info('getPrivateAlbum failed. message = ', err);
} }
}) });
} }
``` ```
### createAsset ### getPrivateAlbum
createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise&lt;FileAsset>; getPrivateAlbum(type: PrivateAlbumType): Promise&lt;FetchResult&lt;PrivateAlbum&gt;&gt;;
Creates a file asset. This API uses a promise to return the result.
This is a system API. Obtains the system album. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | --------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------ | ---- | ------------------------- |
| mediaType | [MediaType](#mediatype) | Yes | Media type. | | type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. |
| displayName | string | Yes | File name to display. |
| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ----------------- | | --------------------------- | -------------- |
| Promise&lt;[FileAsset](#fileasset)> | Promise used to return the file asset created.| | Promise&lt;[FetchResult](#fetchresult)&lt;[PrivateAlbum](#privatealbum)&gt;&gt; | Promise used to return the album obtained.|
**Example** **Example**
```ts ```ts
async function createAssetDemoPromise() { async function example() {
console.info('createAssetDemo') console.info('getPrivateAlbumDemo');
let mediaType = userfile_manager.MediaType.FILE;
let DIR_DOC = directoryType.DIR_DOCUMENTS;
const path = await userFileMgr.getPublicDirectory(DIR_DOC);
try { try {
let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
console.info('createAsset successfully'); let trashAlbum = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + trashAlbum.albumName);
} catch (err) { } catch (err) {
console.info('createAsset failed, message = ', err); console.info('getPrivateAlbum failed. message = ', err);
} }
} }
``` ```
### deleteAsset ### getAudioAssets
deleteAsset(uri: string, callback: AsyncCallback&lt;void>): void; getAudioAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
Deletes a file asset. This API uses an asynchronous callback to return the result.
This is a system API. Obtains audio assets. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_AUDIO
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------- | | -------- | ------------------------ | ---- | ------------------------- |
| uri | string | Yes | URI of the file to delete. | | options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Yes | Callback invoked to return the audio assets obtained.|
**Example** **Example**
```ts ```ts
async function deleteAssetDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('deleteAssetDemo')
let fileKeyObj = userfile_manager.FileKey async function example() {
let fileType = userfile_manager.MediaType.FILE console.info('getAudioAssets');
let option = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: '', let fetchOptions = {
selectionArgs: [], fetchColumns: [],
predicates: predicates
}; };
try {
const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option);
var asset = await fetchFileResult.getFirstObject();
} catch(err) {
console.info('fetch failed, message =', err)
}
if (asset == undefined) { mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => {
console.error('asset not exist') if (fetchResult != undefined) {
return console.info('fetchFileResult success');
let fileAsset = await fetchResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
} }
userFileMgr.deleteAsset(asset.uri, (err) => {
if (err == undefined) {
console.info("deleteAsset successfully");
} else { } else {
console.info("deleteAsset failed with error:"+ err); console.info('fetchFileResult fail' + err);
} }
}); });
} }
``` ```
### deleteAsset ### getAudioAssets
deleteAsset(uri: string): Promise&lt;void>; getAudioAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
Deletes a file asset. This API uses a promise to return the result.
This is a system API. Obtains audio assets. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_AUDIO
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | -------- | ------------------------ | ---- | ------------------------- |
| uri | string | Yes | URI of the file to delete.| | options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------- | --------------------------------- | | --------------------------- | -------------- |
| Promise&lt;void> | Promise used to return the result.| | Promise&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Promise used to return the audio assets obtained.|
**Example** **Example**
```ts ```ts
async function deleteAssetDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('deleteAssetDemo')
let fileKeyObj = userfile_manager.FileKey async function example() {
let fileType = userfile_manager.MediaType.FILE console.info('getAudioAssets');
let option = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: '', let fetchOptions = {
selectionArgs: [], fetchColumns: [],
predicates: predicates
}; };
try { try {
const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); var fetchResult = await mgr.getAudioAssets(fetchOptions);
var asset = await fetchFileResult.getFirstObject(); } catch (err) {
} catch(err) { console.info('getAudioAssets failed, message = ', err);
console.info('fetch failed, message =', err)
} }
if (asset == undefined) {
console.error('asset not exist') if (fetchResult != undefined) {
return console.info('fetchFileResult success');
let fileAsset = await fetchResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
} }
try {
await userFileMgr.deleteAsset(asset.uri);
console.info("deleteAsset successfully");
} catch (err) {
console.info("deleteAsset failed with error:"+ err);
} }
} }
``` ```
### delete
### getAlbums delete(uri: string, callback: AsyncCallback&lt;void&gt;): void;
getAlbums(type: Array&lt;MediaType&gt;, options: MediaFetchOptions, callback: AsyncCallback<Array&lt;Album&gt;&gt;): void;
Obtains albums. This API uses an asynchronous callback to return the result. Deletes a media file. This API uses an asynchronous callback to return the result. The deleted file is moved to the recycle bin.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | --------------------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | | uri | string | Yes | URI of the media file to delete.|
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
| callback | AsyncCallback&lt;Array&lt;[Album](#album)>&gt; | Yes | Callback invoked to return the album list.|
**Example** **Example**
```ts ```ts
async function getAlbumsDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('getAlbumsDemo')
let AlbumNoArgsfetchOp = { async function example() {
selections: '', console.info('deleteAssetDemo');
selectionArgs: [], let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOptions = {
fetchColumns: [],
predicates: predicates
}; };
userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { try {
if (albumList != undefined) { const fetchResult = await mgr.getPhotoAssets(fetchOptions);
const album = albumList[0]; var asset = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + album.albumName); } catch (err) {
console.info('album.count = ' + albumList.length); console.info('fetch failed, message =', err);
}
if (asset == undefined) {
console.error('asset not exist');
return;
}
mgr.delete(asset.uri, (err) => {
if (err == undefined) {
console.info("delete successfully");
} else { } else {
console.info('getAlbum fail, message = ' + err); console.info("delete failed with error:" + err);
} }
}) });
} }
``` ```
### delete
### getAlbums delete(uri: string): Promise&lt;void&gt;;
getAlbums(type: Array&lt;MediaType>, options: MediaFetchOptions): Promise<Array&lt;Album>>; Deletes a media file. This API uses a promise to return the result. The deleted file is moved to the recycle bin.
Obtains albums. This API uses a promise to return the result. **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | -------------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)> | Yes | Type of the media data to obtain.| | uri | string | Yes | URI of the media file to delete.|
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------ | -------------------------- | | --------------------------------------- | ----------------- |
| Promise<Array&lt;[Album](#album)>> | Promise used to return the album list.| | Promise&lt;void&gt;| Promise that returns no value.|
**Example** **Example**
```ts ```ts
async function getAlbumsDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('getAlbumsDemo')
let AlbumNoArgsfetchOp = { async function example() {
selections: '', console.info('deleteDemo');
selectionArgs: [], let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOptions = {
fetchColumns: [],
predicates: predicates
}; };
try { try {
let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); const fetchResult = await mgr.getPhotoAssets(fetchOptions);
const album = albumList[0]; var asset = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + album.albumName); } catch (err) {
console.info('album.count = ' + albumList.length); console.info('fetch failed, message =', err);
}
if (asset == undefined) {
console.error('asset not exist');
return;
}
try {
await mgr.delete(asset.uri);
console.info("delete successfully");
} catch (err) { } catch (err) {
console.info('getAlbum fail, message = ' + err); console.info("delete failed with error:" + err);
} }
} }
``` ```
### getPrivateAlbum ### on
getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback<Array&lt;VirtualAlbum&gt;>): void
Obtains the system album. This API uses an asynchronous callback to return the result. on(type: ChangeEvent, callback: Callback&lt;void&gt;): void
This is a system API. Subscribes to changes of the file management library. This API uses a callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------- | | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain. | | type | [ChangeEvent](#changeevent) | Yes | Type of event to subscribe to.<br>**deviceChange** indicates the device change.<br>**albumChange** indicates the album change.<br>**imageChange** indicates the image change.<br>**audioChange** indicates the audio file change.<br>**videoChange** indicates the video file change.<br>**remoteFileChange** indicates the file change on the registered device.|
| callback | AsyncCallback<Array&lt;[VirtualAlbum](#virtualalbum)>> | Yes | Callback invoked to return the system album obtained.| | callback | Callback&lt;void&gt; | Yes | Callback that returns no value. |
**Example** **Example**
```ts ```ts
async function getPrivateAlbumDemoCallback() { async function example() {
console.info('getPrivateAlbumDemo') console.info('onDemo');
userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { let count = 0;
if (err == undefined) { mgr.on('imageChange', () => {
console.info('getPrivateAlbum ok'); count++;
// Image file changed. Do something.
});
try { try {
let fetchOpt = { let testFileName = "testFile" + Date.now() + ".jpg";
selections: '', let fileAsset = await mgr.createPhotoAsset(testFileName);
selectionArgs: [], console.info('createPhotoAsset file displayName' + fileAsset.displayName);
}; console.info('createPhotoAsset successfully');
let trashAlbum = albumArray[0];
var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt);
} catch (err) { } catch (err) {
console.info('getFileAssets failed. message = ', err); console.info('createPhotoAsset failed, message = ' + err);
} }
// Get file count in trash album //sleep 1s
let count = fetchResult.getCount(); if (count > 0) {
console.info('fetchResult count = ', count) console.info("onDemo success");
// Get fileAssets in trash album
let trashAsset = await fetchResult.getFirstObject();
// Get file trashed date
let isTrash = trashAsset.isTrash();
console.info('is trashed', isTrash)
} else { } else {
console.info('getPrivateAlbum failed. message = ', err); console.info("onDemo fail");
} }
mgr.off('imageChange', () => {
// Unsubscription succeeds.
}); });
} }
``` ```
### getPrivateAlbum ### off
getPrivateAlbum(type: VirtualAlbumType): Promise<Array&lt;VirtualAlbum&gt;>
Obtains the system album. This API uses a promise to return the result. off(type: ChangeEvent, callback?: Callback&lt;void&gt;): void
This is a system API. Unsubscribes from changes of the file management library. This API uses a callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | ---------------- | ---- | ------------ | | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain.| | type | [ChangeEvent](#changeevent) | Yes | Type of event to subscribe to.<br>**deviceChange** indicates the device change.<br>**albumChange** indicates the album change.<br>**imageChange** indicates the image change.<br>**audioChange** indicates the audio file change.<br>**videoChange** indicates the video file change.<br>**remoteFileChange** indicates the file change on the registered device.|
| callback | Callback&lt;void&gt; | No | Callback that returns no value. |
**Return value**
| Type | Description |
| ------------------------------- | --------------------------------- |
| Promise<Array&lt;[VirtualAlbum](#virtualalbum)>> | Promise used to return the system album obtained.|
**Example** **Example**
```ts ```ts
async function getPrivateAlbumDemoPromise() { async function example() {
console.info('getPrivateAlbumDemo'); console.info('offDemo');
try { let count = 0;
var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); mgr.on('imageChange', () => {
} catch(err) { count++;
console.info('getPrivateAlbum failed. message = ', err); // Image file changed. Do something.
} });
mgr.off('imageChange', () => {
// Unsubscription succeeds.
});
try { try {
let fetchOpt = { let testFileName = "testFile" + Date.now() + ".jpg";
selections: '', let fileAsset = await mgr.createPhotoAsset(testFileName);
selectionArgs: [], console.info('createPhotoAsset file displayName' + fileAsset.displayName);
}; console.info('createPhotoAsset successfully');
let trashAlbum = albumArray[0];
var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt);
} catch (err) { } catch (err) {
console.info('getFileAssets failed. message = ', err); console.info('createPhotoAsset failed, message = ' + err);
}
//sleep 1s
if (count == 0) {
console.info("offDemo success");
} else {
console.info("offDemo fail");
} }
// Get file count in trash album
let count = fetchResult.getCount();
console.info('fetchResult count = ', count)
// Get fileAssets in trash album
let trashAsset = await fetchResult.getFirstObject();
// Get file trashed date
let isTrash = trashAsset.isTrash();
console.info('is trashed', isTrash)
} }
``` ```
### getActivePeers ### getActivePeers
getActivePeers(callback: AsyncCallback<Array&lt;PeerInfo>>): void; getActivePeers(callback: AsyncCallback&lt;Array&lt;PeerInfo&gt;&gt;): void;
Obtains information about online peer devices. This API uses an asynchronous callback to return the result. Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
This is a system API.
**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ------------ | | -------- | --------------------------------- | ---- | ------------ |
| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the online device list.| | callback | AsyncCallback&lt;Array&lt;[PeerInfo](#peerinfo)&gt;&gt; | Yes | Callback invoked to return the online peer device list.|
**Example** **Example**
```ts ```ts
async function getActivePeersDemoCallback() { async function example() {
console.info('getActivePeersDemo') console.info('getActivePeersDemo');
var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { mgr.getActivePeers((err, devicesInfo) => {
if (err == undefined) { if (devicesInfo != undefined) {
console.log('getActivePeers succeed.') console.log('getActivePeers succeed.');
for (let i = 0; i < devicesInfo.length; i++) { for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
} }
} else { } else {
console.info('getActivePeers failed. message = ', err) console.info('getActivePeers failed. message = ', err);
} }
}); });
} }
...@@ -688,70 +743,66 @@ async function getActivePeersDemoCallback() { ...@@ -688,70 +743,66 @@ async function getActivePeersDemoCallback() {
### getActivePeers ### getActivePeers
getActivePeers(): Promise<Array&lt;PeerInfo>>; getActivePeers(): Promise&lt;Array&lt;PeerInfo&gt;&gt;;
Obtains information about online peer devices. This API uses a promise to return the result. Obtains information about online peer devices. This API uses a promise to return the result.
This is a system API.
**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------- | ----------------------------- | | --------------------------- | ----------------------------- |
| Promise<Array<[PeerInfo](#peerinfo)>> | Promise used to return the online device list.| | Promise&lt;Array&lt;[PeerInfo](#peerinfo)&gt;&gt; | Promise used to return the online device list.|
**Example** **Example**
```ts ```ts
async function getActivePeersDemoPromise() { async function example() {
console.info('getActivePeersDemo') console.info('getActivePeersDemo');
try { try {
var devicesInfo = await userFileMgr.getActivePeers(); var devicesInfo = await mgr.getActivePeers();
} catch (err) { } catch (err) {
console.info('getActivePeers failed. message = ', err) console.info('getActivePeers failed. message = ', err);
} }
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
console.log('getActivePeers succeed.') console.log('getActivePeers succeed.');
for (let i = 0; i < devicesInfo.length; i++) { for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
} }
} else { } else {
console.info('get distributed fail') console.info('get distributed fail');
} }
} }
``` ```
### getAllPeers ### getAllPeers
getAllPeers(callback: AsyncCallback<Array&lt;PeerInfo>>): void; getAllPeers(callback: AsyncCallback&lt;Array&lt;PeerInfo&gt;&gt;): void;
Obtains information about all peer devices. This API uses an asynchronous callback to return the result. Obtains information about all peer devices. This API uses an asynchronous callback to return the result.
This is a system API.
**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ------------ | | -------- | --------------------------------- | ---- | ------------ |
| callback | AsyncCallback<Array&lt;[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the peer device list.| | callback | AsyncCallback&lt;Array&lt;[PeerInfo](#peerinfo)&gt;&gt; | Yes | Callback invoked to return the online peer device list.|
**Example** **Example**
```ts ```ts
async function getAllPeersDemoCallback() { async function example() {
console.info('getAllPeersDemo') console.info('getAllPeersDemo');
var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { mgr.getAllPeers((err, devicesInfo) => {
if (err == undefined) { if (devicesInfo != undefined) {
console.log('getAllPeers succeed.') console.log('getAllPeers succeed.');
for (let i = 0; i < devicesInfo.length; i++) { for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
} }
} else { } else {
console.info('getAllPeers failed. message = ', err) console.info('getAllPeers failed. message = ', err);
} }
}); });
} }
...@@ -759,37 +810,35 @@ async function getAllPeersDemoCallback() { ...@@ -759,37 +810,35 @@ async function getAllPeersDemoCallback() {
### getAllPeers ### getAllPeers
getAllPeers(): Promise<Array&lt;PeerInfo>>; getAllPeers(): Promise&lt;Array&lt;PeerInfo&gt;&gt;;
Obtains information about all peer devices. This API uses a promise to return the result. Obtains information about all peer devices. This API uses a promise to return the result.
This is a system API.
**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------- | ----------------------------- | | --------------------------- | ----------------------------- |
| Promise<Array&lt;[PeerInfo](#peerinfo)>> | Promise used to return the peer device list.| | Promise&lt;Array&lt;[PeerInfo](#peerinfo)&gt;&gt; | Promise used to return the peer device list.|
**Example** **Example**
```ts ```ts
async function getAllPeersDemoPromise() { async function example() {
console.info('getAllPeersDemo') console.info('getAllPeersDemo');
try { try {
var devicesInfo = await userFileMgr.getAllPeers(); var devicesInfo = await mgr.getAllPeers();
} catch (err) { } catch (err) {
console.info('getAllPeers failed. message = ', err) console.info('getAllPeers failed. message = ', err);
} }
if (devicesInfo != undefined) { if (devicesInfo != undefined) {
console.log('getAllPeers succeed.') console.log('getAllPeers succeed.');
for (let i = 0; i < devicesInfo.length; i++) { for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
} }
} else { } else {
console.info('get distributed fail') console.info('get distributed fail');
} }
} }
``` ```
...@@ -807,20 +856,20 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us ...@@ -807,20 +856,20 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------------- | | -------- | ------------------------- | ---- | -------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
**Example** **Example**
```ts ```ts
async function releaseDemoCallback() { async function example() {
console.info('releaseDemo'); console.info('releaseDemo');
userFileMgr.release((err) => { mgr.release((err) => {
if (err != undefined) { if (err != undefined) {
console.info('release failed. message = ', err); console.info('release failed. message = ', err);
} else { } else {
console.info('release ok.'); console.info('release ok.');
} }
}) });
} }
``` ```
...@@ -837,15 +886,15 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us ...@@ -837,15 +886,15 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us
| Type | Description | | Type | Description |
| ------------------- | --------------------------------- | | ------------------- | --------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
```ts ```ts
async function releaseDemoPromise() { async function example() {
console.info('releaseDemo'); console.info('releaseDemo');
try { try {
await userFileMgr.release(); await mgr.release();
console.info('release ok.'); console.info('release ok.');
} catch (err) { } catch (err) {
console.info('release failed. message = ', err); console.info('release failed. message = ', err);
...@@ -864,79 +913,83 @@ Provides APIs for encapsulating file asset attributes. ...@@ -864,79 +913,83 @@ Provides APIs for encapsulating file asset attributes.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | | ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | | uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. |
| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | | fileType | [FileType](#filetype) | Yes | No | Type of the file. |
| displayName | string | Yes | Yes | File name, including the file name extension, to display. | | displayName | string | Yes | Yes | File name, including the file name extension, to display. |
### isDirectory ### get
isDirectory(callback: AsyncCallback&lt;boolean&gt;): void get(member: string): MemberType;
Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. Obtains the value of a **FileAsset** parameter.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ------------------- | | -------- | ------------------------- | ---- | ----- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| | member | string | Yes | Name of the parameter to obtain, for example, **ImageVideoKey.URI**.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('fileAssetGetDemo');
let imageType = mediaLibrary.MediaType.IMAGE; try {
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: fileKeyObj.MEDIA_TYPE + '= ?', let fetchOption = {
selectionArgs: [imageType.toString()], fetchColumns: [],
order: fileKeyObj.DATE_ADDED + " DESC", predicates: predicates
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let title = userFileManager.ImageVideoKey.TITLE;
asset.isDirectory((err, isDirectory) => { let fileAssetTitle = fileAsset.get(title.toString());
// do something console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle);
}); } catch (err) {
console.info('release failed. message = ', err);
}
} }
``` ```
### isDirectory ### set
isDirectory():Promise&lt;boolean&gt; set(member: string, value: string): void;
Checks whether this file asset is a directory. This API uses a promise to return the result. Sets a **FileAsset** parameter.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Return value** **Parameters**
| Type | Description | | Name | Type | Mandatory | Description |
| ---------------------- | ---------------------------- | | -------- | ------------------------- | ---- | ----- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| | member | string | Yes | Name of the parameter to set, for example, **ImageVideoKey.URI**.|
| value | string | Yes | Value to set. Only the value of **ImageVideoKey.TITLE** can be changed.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = userfile_manager.FileKey console.info('fileAssetSetDemo');
let imageType = userfile_manager.MediaType.IMAGE; try {
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: fileKeyObj.MEDIA_TYPE + '= ?', let fetchOption = {
selectionArgs: [imageType.toString()], fetchColumns: [],
order: fileKeyObj.DATE_ADDED + " DESC", predicates: predicates
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let title = userFileManager.ImageVideoKey.TITLE;
asset.isDirectory().then(function(isDirectory){ fileAsset.set(title.toString(), "newTitle");
console.info("isDirectory result:"+ isDirectory); } catch (err) {
}).catch(function(err){ console.info('release failed. message = ', err);
console.info("isDirectory failed with error:"+ err); }
});
} }
``` ```
...@@ -946,7 +999,7 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void ...@@ -946,7 +999,7 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void
Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -958,22 +1011,29 @@ Commits the modification on the file metadata to the database. This API uses an ...@@ -958,22 +1011,29 @@ Commits the modification on the file metadata to the database. This API uses an
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('commitModifyDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let title = userFileManager.ImageVideoKey.TITLE;
asset.title = 'newtitle'; let fileAssetTitle = fileAsset.get(title.toString());
asset.commitModify(() => { console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle);
console.info('commitModify success'); fileAsset.set(title.toString(), "newTitle");
fileAsset.commitModify((err) => {
if (err == undefined) {
let newFileAssetTitle = fileAsset.get(title.toString());
console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle);
} else {
console.info('commitModify failed, message =', err);
}
}); });
} }
``` ```
...@@ -984,7 +1044,7 @@ commitModify(): Promise&lt;void&gt; ...@@ -984,7 +1044,7 @@ commitModify(): Promise&lt;void&gt;
Commits the modification on the file metadata to the database. This API uses a promise to return the result. Commits the modification on the file metadata to the database. This API uses a promise to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -996,21 +1056,29 @@ Commits the modification on the file metadata to the database. This API uses a p ...@@ -996,21 +1056,29 @@ Commits the modification on the file metadata to the database. This API uses a p
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('commitModifyDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let title = userFileManager.ImageVideoKey.TITLE;
asset.title = 'newtitle'; let fileAssetTitle = fileAsset.get(title.toString());
asset.commitModify(); console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle);
fileAsset.set(title.toString(), "newTitle");
try {
await fileAsset.commitModify();
let newFileAssetTitle = fileAsset.get(title.toString());
console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle);
} catch (err) {
console.info('release failed. message = ', err);
}
} }
``` ```
...@@ -1020,9 +1088,11 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void ...@@ -1020,9 +1088,11 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void
Opens this file asset. This API uses an asynchronous callback to return the result. Opens this file asset. This API uses an asynchronous callback to return the result.
**NOTE**<br>Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. >**NOTE**
>
>The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1036,18 +1106,17 @@ Opens this file asset. This API uses an asynchronous callback to return the resu ...@@ -1036,18 +1106,17 @@ Opens this file asset. This API uses an asynchronous callback to return the resu
**Example** **Example**
```js ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; console.info('openDemo');
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let testFileName = "testFile" + Date.now() + ".jpg";
let userFileMgr = userfile_manager.getUserFileMgr(context); const fileAsset = await mgr.createPhotoAsset(testFileName);
const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); fileAsset.open('rw', (err, fd) => {
const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); if (fd != undefined) {
asset.open('rw', (openError, fd) => { console.info('File fd' + fd);
if(fd > 0){ fileAsset.close(fd);
asset.close(fd); } else {
}else{ console.info('File err' + err);
console.info('File Open Failed!' + openError);
} }
}); });
} }
...@@ -1059,9 +1128,11 @@ open(mode: string): Promise&lt;number&gt; ...@@ -1059,9 +1128,11 @@ open(mode: string): Promise&lt;number&gt;
Opens this file asset. This API uses a promise to return the result. Opens this file asset. This API uses a promise to return the result.
**NOTE**<br>Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. >**NOTE**
>
>The write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1079,20 +1150,22 @@ Opens this file asset. This API uses a promise to return the result. ...@@ -1079,20 +1150,22 @@ Opens this file asset. This API uses a promise to return the result.
**Example** **Example**
```js ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; console.info('openDemo');
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; try {
let userFileMgr = userfile_manager.getUserFileMgr(context); let testFileName = "testFile" + Date.now() + ".jpg";
const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); const fileAsset = await mgr.createPhotoAsset(testFileName);
const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); let fd = await fileAsset.open('rw');
asset.open('rw') if (fd != undefined) {
.then((fd) => { console.info('File fd' + fd);
console.info('File fd!' + fd); fileAsset.close(fd);
}) } else {
.catch((err) => { console.info(' open File fail');
console.info('File err!' + err); }
}); } catch (err) {
console.info('open Demo err' + err);
}
} }
``` ```
...@@ -1113,33 +1186,31 @@ Closes this file asset. This API uses an asynchronous callback to return the res ...@@ -1113,33 +1186,31 @@ Closes this file asset. This API uses an asynchronous callback to return the res
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('closeDemo');
let imageType = mediaLibrary.MediaType.IMAGE; try {
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: fileKeyObj.MEDIA_TYPE + '= ?', let fetchOption = {
selectionArgs: [imageType.toString()], fetchColumns: [],
order: fileKeyObj.DATE_ADDED + " DESC", predicates: predicates
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const fileAsset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let fd = await fileAsset.open('rw');
asset.open('rw').then((fd) => { console.info('file fd', fd);
console.info('File fd!' + fd); fileAsset.close(fd, (err) => {
asset.close(fd, (closeErr) => { if (err == undefined) {
if (closeErr != undefined) { console.info('asset close succeed.');
console.info('mediaLibraryTest : close : FAIL ' + closeErr);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else { } else {
console.info("=======asset.close success====>"); console.info('close failed, message = ' + err);
} }
}); });
}) } catch (err) {
.catch((err) => { console.info('close failed, message = ' + err);
console.info('File err!' + err); }
});
} }
``` ```
...@@ -1165,34 +1236,26 @@ Closes this file asset. This API uses a promise to return the result. ...@@ -1165,34 +1236,26 @@ Closes this file asset. This API uses a promise to return the result.
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('closeDemo');
let imageType = mediaLibrary.MediaType.IMAGE; try {
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: fileKeyObj.MEDIA_TYPE + '= ?', let fetchOption = {
selectionArgs: [imageType.toString()], fetchColumns: [],
order: fileKeyObj.DATE_ADDED + " DESC", predicates: predicates
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); let fd = await asset.open('rw');
asset.open('rw').then((fd) => { console.info('file fd', fd);
console.info('File fd!' + fd); await asset.close(fd);
asset.close(fd).then((closeErr) => { console.info('asset close succeed.');
if (closeErr != undefined) { } catch (err) {
console.info('mediaLibraryTest : close : FAIL ' + closeErr); console.info('close failed, message = ' + err);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else {
console.info("=======asset.close success====>");
} }
});
})
.catch((err) => {
console.info('File err!' + err);
});
} }
``` ```
...@@ -1202,7 +1265,7 @@ getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void ...@@ -1202,7 +1265,7 @@ 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. Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1210,36 +1273,40 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ...@@ -1210,36 +1273,40 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------- | | -------- | ----------------------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.| | callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey console.info('getThumbnailDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); console.info('asset displayName = ', asset.displayName);
asset.getThumbnail((err, pixelmap) => { asset.getThumbnail((err, pixelMap) => {
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); if (err == undefined) {
console.info('getThumbnail successful ' + pixelMap);
} else {
console.info('getThumbnail fail', err);
}
}); });
} }
``` ```
### getThumbnail ### getThumbnail
getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void getThumbnail(size: image.Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void
Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1247,38 +1314,42 @@ Obtains the file thumbnail of the given size. This API uses an asynchronous call ...@@ -1247,38 +1314,42 @@ Obtains the file thumbnail of the given size. This API uses an asynchronous call
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---------------- | | -------- | ----------------------------------- | ---- | ---------------- |
| size | [Size](#size) | Yes | Size of the thumbnail to obtain. | | size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail to obtain. |
| callback | AsyncCallback&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.| | callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback invoked to return the pixel map of the thumbnail.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getThumbnailDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); console.info('asset displayName = ', asset.displayName);
asset.getThumbnail(size, (err, pixelmap) => { asset.getThumbnail(size, (err, pixelMap) => {
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); if (err == undefined) {
console.info('getThumbnail successful ' + pixelMap);
} else {
console.info('getThumbnail fail', err);
}
}); });
} }
``` ```
### getThumbnail ### getThumbnail
getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt; getThumbnail(size?: image.Size): Promise&lt;image.PixelMap&gt;
Obtains the file thumbnail of the given size. This API uses a promise to return the result. Obtains the file thumbnail of the given size. This API uses a promise to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1286,36 +1357,34 @@ Obtains the file thumbnail of the given size. This API uses a promise to return ...@@ -1286,36 +1357,34 @@ Obtains the file thumbnail of the given size. This API uses a promise to return
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | -------------- | ---- | ----- | | ---- | -------------- | ---- | ----- |
| size | [Size](#size) | No | Size of the thumbnail to obtain.| | size | [image.Size](js-apis-image.md#size) | No | Size of the thumbnail to obtain.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | --------------------- | | ----------------------------- | --------------------- |
| Promise&lt;[image.PixelMap](../apis/js-apis-image.md#pixelmap7)&gt; | Promise used to return the pixel map of the thumbnail.| | Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the pixel map of the thumbnail.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getThumbnailDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); console.info('asset displayName = ', asset.displayName);
asset.getThumbnail(size) asset.getThumbnail(size).then((pixelMap) => {
.then((pixelmap) => { console.info('getThumbnail successful ' + pixelMap);
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); }).catch((err) => {
}) console.info('getThumbnail fail' + err);
.catch((err) => {
console.info('mediaLibraryTest : getThumbnail fail'+ err);
}); });
} }
``` ```
...@@ -1326,7 +1395,7 @@ favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void ...@@ -1326,7 +1395,7 @@ 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. Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1339,21 +1408,24 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback ...@@ -1339,21 +1408,24 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('favoriteDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); asset.favorite(true, (err) => {
asset.favorite(true,function(err){ if (err == undefined) {
// Do something. console.info("favorite successfully");
} else {
console.info("favorite failed with error:" + err);
}
}); });
} }
``` ```
...@@ -1364,7 +1436,7 @@ favorite(isFavorite: boolean): Promise&lt;void&gt; ...@@ -1364,7 +1436,7 @@ favorite(isFavorite: boolean): Promise&lt;void&gt;
Favorites or unfavorites this file asset. This API uses a promise to return the result. Favorites or unfavorites this file asset. This API uses a promise to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -1382,267 +1454,27 @@ Favorites or unfavorites this file asset. This API uses a promise to return the ...@@ -1382,267 +1454,27 @@ Favorites or unfavorites this file asset. This API uses a promise to return the
**Example** **Example**
```js ```ts
async function example() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.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
isFavorite(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ----------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.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
isFavorite():Promise&lt;boolean&gt;
Checks whether this file asset is favorited. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Return value**
| Type | Description |
| ---------------------- | ------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.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
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.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| 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 | Callback that returns no value. |
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.trash(true, trashCallBack);
function trashCallBack(err, trash) {
console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash');
}
}
```
### trash
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.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| 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.|
**Return value**
| Type | Description |
| ------------------- | ---------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.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
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.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | --------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isTrash((err, isTrash) => {
if (isTrash == undefined) {
console.error('Failed to get trash state: ' + err);
return;
}
console.info('Get trash state success: ' + isTrash);
});
}
```
### isTrash
isTrash():Promise&lt;boolean&gt;
Checks whether this file asset is in the trash. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Return value**
| Type | Description |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise used to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.|
**Example**
```js
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('favoriteDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const asset = await fetchResult.getFirstObject();
const asset = await fetchFileResult.getFirstObject(); asset.favorite(true).then(function () {
asset.isTrash().then(function(isTrash){ console.info("favorite successfully");
console.info("isTrash result: " + isTrash); }).catch(function (err) {
}).catch(function(err){ console.info("favorite failed with error:" + err);
console.error("isTrash failed with error: " + err);
}); });
} }
``` ```
## FetchFileResult ## FetchResult
Provides APIs to manage the file retrieval result. Provides APIs to manage the file retrieval result.
...@@ -1662,19 +1494,19 @@ Obtains the total number of files in the result set. ...@@ -1662,19 +1494,19 @@ Obtains the total number of files in the result set.
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getCountDemo');
let fileType = mediaLibrary.MediaType.FILE; let predicates = new dataSharePredicates.DataSharePredicates();
let getFileCountOneOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [fileType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); const fetchCount = fetchResult.getCount();
const fetchCount = fetchFileResult.getCount(); console.info('fetchCount = ', fetchCount);
} }
``` ```
...@@ -1694,30 +1526,23 @@ Checks whether the cursor is in the last row of the result set. ...@@ -1694,30 +1526,23 @@ Checks whether the cursor is in the last row of the result set.
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let predicates = new dataSharePredicates.DataSharePredicates();
let imageType = mediaLibrary.MediaType.IMAGE; let fetchOption = {
let getImageOp = { fetchColumns: [],
selections: fileKeyObj.MEDIA_TYPE + '= ?', predicates: predicates
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); const fetchCount = fetchResult.getCount();
const fetchCount = fetchFileResult.getCount(); console.info('count:' + fetchCount);
console.info('mediaLibraryTest : count:' + fetchCount); let fileAsset = await fetchResult.getLastObject();
let fileAsset = await fetchFileResult.getFirstObject(); if (!fetchResult.isAfterLast()) {
for (var i = 1; i < fetchCount; i++) { console.info('fileAsset isAfterLast displayName = ', fileAsset.displayName);
fileAsset = await fetchFileResult.getNextObject(); } else {
if(i == fetchCount - 1) { console.info('fileAsset not isAfterLast ');
console.info('mediaLibraryTest : isLast');
var result = fetchFileResult.isAfterLast();
console.info('mediaLibraryTest : isAfterLast:' + result);
console.info('mediaLibraryTest : isAfterLast end');
fetchFileResult.close();
}
} }
} }
``` ```
...@@ -1732,25 +1557,29 @@ Releases and invalidates this **FetchFileResult** instance. After this instance ...@@ -1732,25 +1557,29 @@ Releases and invalidates this **FetchFileResult** instance. After this instance
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('fetchResultCloseDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); try {
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fetchResult = await mgr.getPhotoAssets(fetchOption);
fetchFileResult.close(); await fetchResult.close();
console.info('close succeed.');
} catch (err) {
console.info('close fail. message = ' + err);
}
} }
``` ```
### getFirstObject ### getFirstObject
getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void getFirstObject(callback: AsyncCallback&lt;T&gt;): void
Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.
...@@ -1760,35 +1589,34 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca ...@@ -1760,35 +1589,34 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------- | ---- | ------------------------------------------- | | -------- | --------------------------------------------- | ---- | ------------------------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the first file asset.| | callback | AsyncCallback&lt;T&gt; | Yes | Callback invoked to return the first file asset.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getFirstObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); fetchResult.getFirstObject((err, fileAsset) => {
fetchFileResult.getFirstObject((err, fileAsset) => { if (fileAsset != undefined) {
if (err) { console.info('fileAsset displayName: ', fileAsset.displayName);
console.error('Failed '); } else {
return; console.info("fileAsset failed with err:" + err);
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName); });
})
} }
``` ```
### getFirstObject ### getFirstObject
getFirstObject(): Promise&lt;FileAsset&gt; getFirstObject(): Promise&lt;T&gt;
Obtains the first file asset in the result set. This API uses a promise to return the result. Obtains the first file asset in the result set. This API uses a promise to return the result.
...@@ -1798,33 +1626,29 @@ Obtains the first file asset in the result set. This API uses a promise to retur ...@@ -1798,33 +1626,29 @@ Obtains the first file asset in the result set. This API uses a promise to retur
| Type | Description | | Type | Description |
| --------------------------------------- | -------------------------- | | --------------------------------------- | -------------------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | Promise used to return the first file asset.| | Promise&lt;T&gt; | Promise used to return the first file asset.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getFirstObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getFirstObject();
fetchFileResult.getFirstObject().then(function(fileAsset){ console.info('fileAsset displayName: ', fileAsset.displayName);
console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset));
}).catch(function(err){
console.info("getFirstObject failed with error:"+ err);
});
} }
``` ```
### getNextObject ### getNextObject
getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void getNextObject(callback: AsyncCallback&lt;T&gt;): void
Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
...@@ -1834,35 +1658,37 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal ...@@ -1834,35 +1658,37 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------- | ---- | ----------------------------------------- | | --------- | --------------------------------------------- | ---- | ----------------------------------------- |
| callbacke | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the next file asset.| | callbacke | AsyncCallback&lt;T&gt; | Yes | Callback invoked to return the next file asset.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getNextObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); await fetchResult.getFirstObject();
fetchFileResult.getNextObject((err, fileAsset) => { if (fetchResult.isAfterLast()) {
if (err) { fetchResult.getNextObject((err, fileAsset) => {
console.error('Failed '); if (fileAsset != undefined) {
return; console.info('fileAsset displayName: ', fileAsset.displayName);
} else {
console.info("fileAsset failed with err:" + err);
}
});
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName);
})
} }
``` ```
### getNextObject ### getNextObject
getNextObject(): Promise&lt;FileAsset&gt; getNextObject(): Promise&lt;T&gt;
Obtains the next file asset in the result set. This API uses a promise to return the result. Obtains the next file asset in the result set. This API uses a promise to return the result.
...@@ -1872,31 +1698,32 @@ Obtains the next file asset in the result set. This API uses a promise to return ...@@ -1872,31 +1698,32 @@ Obtains the next file asset in the result set. This API uses a promise to return
| Type | Description | | Type | Description |
| --------------------------------------- | ----------------- | | --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | Promise used to return the next file asset.| | Promise&lt;T&gt; | Promise used to return the next file asset obtained.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getNextObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); await fetchResult.getFirstObject();
const fetchCount = fetchFileResult.getCount(); if (fetchResult.isAfterLast()) {
console.info('mediaLibraryTest : count:' + fetchCount); let fileAsset = await fetchResult.getNextObject();
let fileAsset = await fetchFileResult.getNextObject(); console.info('fileAsset displayName: ', fileAsset.displayName);
}
} }
``` ```
### getLastObject ### getLastObject
getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void getLastObject(callback: AsyncCallback&lt;T&gt;): void
Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.
...@@ -1906,35 +1733,34 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal ...@@ -1906,35 +1733,34 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------- | ---- | --------------------------- | | -------- | --------------------------------------------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the last file asset.| | callback | AsyncCallback&lt;T&gt; | Yes | Callback invoked to return the last file asset obtained.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getLastObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); fetchResult.getLastObject((err, fileAsset) => {
fetchFileResult.getLastObject((err, fileAsset) => { if (fileAsset != undefined) {
if (err) { console.info('fileAsset displayName: ', fileAsset.displayName);
console.error('Failed '); } else {
return; console.info("fileAsset failed with err:" + err);
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName); });
})
} }
``` ```
### getLastObject ### getLastObject
getLastObject(): Promise&lt;FileAsset&gt; getLastObject(): Promise&lt;T&gt;
Obtains the last file asset in the result set. This API uses a promise to return the result. Obtains the last file asset in the result set. This API uses a promise to return the result.
...@@ -1944,29 +1770,29 @@ Obtains the last file asset in the result set. This API uses a promise to return ...@@ -1944,29 +1770,29 @@ Obtains the last file asset in the result set. This API uses a promise to return
| Type | Description | | Type | Description |
| --------------------------------------- | ----------------- | | --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | Promise used to return the last file asset.| | Promise&lt;T&gt; | Promise used to return the last file asset obtained.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getLastObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getLastObject();
let lastObject = await fetchFileResult.getLastObject(); console.info('fileAsset displayName: ', fileAsset.displayName);
} }
``` ```
### getPositionObject ### getPositionObject
getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void getPositionObject(index: number, callback: AsyncCallback&lt;T&gt;): void
Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.
...@@ -1977,35 +1803,34 @@ Obtains a file asset with the specified index in the result set. This API uses a ...@@ -1977,35 +1803,34 @@ Obtains a file asset with the specified index in the result set. This API uses a
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------ | | -------- | ---------------------------------------- | ---- | ------------------ |
| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | | index | number | Yes | Index of the file asset to obtain. The value starts from **0**. |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | Yes | Callback invoked to return the file asset obtained.| | callback | AsyncCallback&lt;T&gt; | Yes | Callback invoked to return the file asset obtained.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getPositionObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); fetchResult.getPositionObject(0, (err, fileAsset) => {
fetchFileResult.getPositionObject(0, (err, fileAsset) => { if (fileAsset != undefined) {
if (err) { console.info('fileAsset displayName: ', fileAsset.displayName);
console.error('Failed '); } else {
return; console.info("fileAsset failed with err:" + err);
} }
console.log('fileAsset.displayName : ' + fileAsset.displayName); });
})
} }
``` ```
### getPositionObject ### getPositionObject
getPositionObject(index: number): Promise&lt;FileAsset&gt; getPositionObject(index: number): Promise&lt;T&gt;
Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.
...@@ -2021,27 +1846,23 @@ Obtains a file asset with the specified index in the result set. This API uses a ...@@ -2021,27 +1846,23 @@ Obtains a file asset with the specified index in the result set. This API uses a
| Type | Description | | Type | Description |
| --------------------------------------- | ----------------- | | --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | Promise used to return the file asset obtained.| | Promise&lt;T&gt; | Promise used to return the file asset obtained.|
**Example** **Example**
```js ```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; console.info('getPositionObjectDemo');
let imageType = mediaLibrary.MediaType.IMAGE; let predicates = new dataSharePredicates.DataSharePredicates();
let getImageOp = { let fetchOption = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', fetchColumns: [],
selectionArgs: [imageType.toString()], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let userFileMgr = userfile_manager.getUserFileMgr(context); let fetchResult = await mgr.getPhotoAssets(fetchOption);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); let fileAsset = await fetchResult.getPositionObject(0);
fetchFileResult.getPositionObject(1) .then(function (fileAsset){ console.info('fileAsset displayName: ', fileAsset.displayName);
console.log('fileAsset.displayName : ' + fileAsset.displayName);
}).catch(function (err) {
console.info("getFileAssets failed with error:" + err);
});
} }
``` ```
...@@ -2059,16 +1880,102 @@ Provides APIs to manage albums. ...@@ -2059,16 +1880,102 @@ Provides APIs to manage albums.
| albumUri | string | Yes | No | Album URI. | | albumUri | string | Yes | No | Album URI. |
| dateModified | number | Yes | No | Date when the album was last modified. | | dateModified | number | Yes | No | Date when the album was last modified. |
| count | number | Yes | No | Number of files in the album.| | count | number | Yes | No | Number of files in the album.|
| relativePath | string | Yes | No | Relative path of the album. |
| coverUri | string | Yes | No | URI of the cover file of the album. | coverUri | string | Yes | No | URI of the cover file of the album.
### getPhotoAssets
getPhotoAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
Obtains image and video assets. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------- |
| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.|
| callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Yes | Callback invoked to return the image and video assets obtained.|
**Example**
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() {
console.info('albumGetFileAssetsDemoCallback');
let predicates = new dataSharePredicates.DataSharePredicates();
let albumFetchOptions = {
predicates: predicates
};
let fetchOption = {
fetchColumns: [],
predicates: predicates
};
const albumList = await mgr.getPhotoAlbums(albumFetchOptions);
const album = await albumList.getFirstObject();
album.getPhotoAssets(fetchOption, (err, albumFetchResult) => {
if (albumFetchResult != undefined) {
console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount());
} else {
console.info("album getPhotoAssets failed with error:" + err);
}
});
}
```
### getPhotoAssets
getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
Obtains image and video assets. This API uses a promise to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------- |
| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.|
| Promise | [FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt; | Yes | Promise used to return the image and video assets obtained.|
**Example**
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() {
console.info('albumGetFileAssetsDemoPromise');
let predicates = new dataSharePredicates.DataSharePredicates();
let albumFetchOptions = {
predicates: predicates
};
let fetchOption = {
fetchColumns: [],
predicates: predicates
};
const albumList = await mgr.getPhotoAlbums(albumFetchOptions);
const album = await albumList.getFirstObject();
album.getPhotoAssets(fetchOption).then((albumFetchResult) => {
console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount());
}).catch((err) => {
console.info("album getFileAssets failed with error:" + err);
});
}
```
### commitModify ### commitModify
commitModify(callback: AsyncCallback&lt;void&gt;): void; commitModify(callback: AsyncCallback&lt;void&gt;): void;
Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result. Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -2081,26 +1988,22 @@ Commits the modification on the album attributes to the database. This API uses ...@@ -2081,26 +1988,22 @@ Commits the modification on the album attributes to the database. This API uses
**Example** **Example**
```ts ```ts
async function commitModifyDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('commitModifyDemo')
let fileKeyObj = userfile_manager.FileKey async function example() {
let imageType = userfile_manager.MediaType.IMAGE; console.info('albumCommitModifyDemo');
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: '', let albumFetchOptions = {
selectionArgs: [], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); const albumList = await mgr.getPhotoAlbums(albumFetchOptions);
let asset = await fetchFileResult.getFirstObject(); const album = await albumList.getFirstObject();
console.info('old displayName:', asset.displayName) album.albumName = 'hello';
asset.displayName = 'newDisplayName'; album.commitModify((err) => {
console.info('new displayName:', asset.displayName) if (err != undefined) {
asset.commitModify((err) => { console.info("commitModify failed with error:" + err);
if (err == undefined) {
console.info('commitModify succeed.')
} else { } else {
console.info('commitModify failed, message =', err); console.info("commitModify successfully");
} }
}); });
} }
...@@ -2112,7 +2015,7 @@ commitModify(): Promise&lt;void&gt;; ...@@ -2112,7 +2015,7 @@ commitModify(): Promise&lt;void&gt;;
Commits the modification on the album attributes to the database. This API uses a promise to return the result. Commits the modification on the album attributes to the database. This API uses a promise to return the result.
**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT **Required permissions**: ohos.permission.WRITE_IMAGEVIDEO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
...@@ -2125,265 +2028,338 @@ Commits the modification on the album attributes to the database. This API uses ...@@ -2125,265 +2028,338 @@ Commits the modification on the album attributes to the database. This API uses
**Example** **Example**
```ts ```ts
async function commitModifyDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('commitModifyDemo')
let fileKeyObj = userfile_manager.FileKey async function example() {
let imageType = userfile_manager.MediaType.IMAGE; console.info('albumCommitModifyDemo');
let getImageOp = { let predicates = new dataSharePredicates.DataSharePredicates();
selections: '', let albumFetchOptions = {
selectionArgs: [], predicates: predicates
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
}; };
let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp);
let asset = await fetchFileResult.getFirstObject();
console.info('old displayName:', asset.displayName)
asset.displayName = 'newDisplayName';
console.info('new displayName:', asset.displayName)
try { try {
await asset.commitModify(); var albumList = await mgr.getPhotoAlbums(albumFetchOptions);
console.info('commitModify succeed.')
} catch (err) { } catch (err) {
console.info('commitModify failed, message =', err); console.info('getPhotoAlbums failed. message = ', err);
} }
const album = await albumList.getFirstObject();
album.albumName = 'hello';
album.commitModify().then(() => {
console.info("commitModify successfully");
}).catch((err) => {
console.info("commitModify failed with error:" + err);
});
} }
``` ```
### getFileAssets ## PrivateAlbum
getFileAssets(type: Array&lt;MediaType&gt;, callback: AsyncCallback&lt;FetchFileResult&gt;): void; Provides APIs for managing the system albums.
### Attributes
Obtains the file assets in this album. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Type | Readable | Writable | Description |
| ------------ | ------ | ---- | ---- | ------- |
| albumName | string | Yes | Yes | Album name. |
| albumUri | string | Yes | No | Album URI. |
| dateModified | number | Yes | No | Date when the album was last modified. |
| count | number | Yes | No | Number of files in the album.|
| coverUri | string | Yes | No | URI of the cover file of the album.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT ### getPhotoAssets
getPhotoAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;FileAsset&gt;&gt;): void;
Obtains image and video assets from a system album. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | Yes | Type of the media data to obtain. | | options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.|
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| | callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Yes | Callback invoked to return the image and video assets obtained.|
**Example** **Example**
```ts ```ts
async function albumGetFileAssetsDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('albumGetFileAssetsDemoCallback2')
let imageType = userfile_manager.MediaType.IMAGE; async function example() {
let AlbumNoArgsfetchOp = { console.info('privateAlbumGetFileAssetsDemoCallback');
selections: '', let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
selectionArgs: [], let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
}; };
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); const trashAlbum = await albumList.getFirstObject();
const album = albumList[0]; trashAlbum.getPhotoAssets(fetchOption, (err, fetchResult) => {
album.getFileAssets([imageType], (err, albumFetchFileResult) => { if (fetchResult != undefined) {
if (err == undefined) { let count = fetchResult.getCount();
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); console.info('fetchResult.count = ', count);
} else { } else {
console.info("getFileAssets failed with error:"+ err); console.info('getFileAssets failed, message = ', err);
} }
}); });
} }
``` ```
### getPhotoAssets
### getFileAssets getPhotoAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&gt;;
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void; Obtains image and video assets from a system album. This API uses a promise to return the result.
Obtains the file assets in this album. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.READ_IMAGEVIDEO
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------- |
| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.|
**Return value**
| Type | Description |
| --------------------------------------- | ----------------- |
| Promise:[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;| Promise used to return the image and video assets obtained.|
**Example**
```ts
import dataSharePredicates from '@ohos.data.dataSharePredicates';
async function example() {
console.info('privateAlbumGetFileAssetsDemoPromise');
let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
};
const trashAlbum = await albumList.getFirstObject();
let fetchResult = await trashAlbum.getPhotoAssets(fetchOption);
let count = fetchResult.getCount();
console.info('fetchResult.count = ', count);
}
```
### delete
delete(uri: string, callback: AsyncCallback&lt;void&gt;): void;
Deletes files from a system album.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | Yes | Type of the media data to obtain. | | uri | string | Yes | Album URI.|
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the media data. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.|
**Example** **Example**
```ts ```ts
async function albumGetFileAssetsDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('albumGetFileAssetsDemoCallback')
let imageType = userfile_manager.MediaType.IMAGE; async function example() {
let AlbumNoArgsfetchOp = { console.info('privateAlbumDeleteCallback');
selections: '', let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
selectionArgs: [], let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
}; };
let fileNoArgsfetchOp = { const trashAlbum = await albumList.getFirstObject();
selections: '', let fetchResult = await trashAlbum.getPhotoAssets(fetchOption);
selectionArgs: [], const fileAsset = await fetchResult.getFirstObject();
} let deleteFileUri = fileAsset.uri;
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); trashAlbum.delete(deleteFileUri, (err) => {
const album = albumList[0]; if (err != undefined) {
album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { console.info('trashAlbum.delete failed, message = ', err);
if (err == undefined) {
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult));
} else { } else {
console.info("getFileAssets failed with error:"+ err); console.info('trashAlbum.delete successfully');
} }
}); });
} }
``` ```
### delete
### getFileAssets delete(uri: string): Promise&lt;void&gt;;
getFileAssets(type: Array&lt;MediaType&gt;, options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;; Deletes files from a system album.
Obtains the file assets in this album. This API uses a promise to return the result.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | -------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | Yes | Type of the media data to obtain. | | uri | string | Yes | Album URI.|
|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the media data.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------------------- | ------------------------- | | --------------------------------------- | ----------------- |
| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| | Promise&lt;void&gt;| Promise that returns no value.|
**Example** **Example**
```ts ```ts
async function albumGetFileAssetsDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('albumGetFileAssetsDemoPromise')
let imageType = userfile_manager.MediaType.IMAGE; async function example() {
let AlbumNoArgsfetchOp = { console.info('privateAlbumDeleteDemoPromise');
selections: '', let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
selectionArgs: [], let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
}; };
let fileNoArgsfetchOp = { const trashAlbum = await albumList.getFirstObject();
selections: '', let fetchResult = await trashAlbum.getPhotoAssets(fetchOption);
selectionArgs: [], const fileAsset = await fetchResult.getFirstObject();
} let deleteFileUri = fileAsset.uri;
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); trashAlbum.delete(deleteFileUri).then(() => {
const album = albumList[0]; console.info('trashAlbum.delete successfully');
album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ }).catch((err) => {
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); console.info('trashAlbum.delete failed, message = ', err);
}).catch(function(err){
console.info("getFileAssets failed with error:"+ err);
}); });
} }
``` ```
## VirtualAlbum
Provides APIs for managing a virtual album.
### getFileAssets ### recover
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void; recover(uri: string, callback: AsyncCallback&lt;void&gt;): void;
Obtains file assets in the virtual album. This API uses an asynchronous callback to return the result. Recovers files in a system album.
This is a system API. **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT
> **NOTE**<br>
> The ability privilege level (APL) of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the Access Control List (ACL). For details, see [ACL](../../security/accesstoken-overview.md#acl).
>
> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | Yes | Type of the media data to obtain. | | uri | string | Yes | Album URI.|
| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback that returns no value.|
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.|
**Example** **Example**
```ts ```ts
async function virtualAlbumGetFileAssetsDemoCallback() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('virtualAlbumGetFileAssetsDemoCallback')
try {
var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH);
} catch (err) {
console.info('getPrivateAlbum failed, message = ', err);
}
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { async function example() {
if (err == undefined) { console.info('privateAlbumRecoverDemoCallback');
let count = fetchResult.getCount(); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
console.info('fetchResult.count = ', count); let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
};
const trashAlbum = await albumList.getFirstObject();
let fetchResult = await trashAlbum.getPhotoAssets(fetchOption);
const fileAsset = await fetchResult.getFirstObject();
let recoverFileUri = fileAsset.uri;
trashAlbum.recover(recoverFileUri, (err) => {
if (err != undefined) {
console.info('trashAlbum.recover failed, message = ', err);
} else { } else {
console.info('getFileAssets failed, message = ', err); console.info('trashAlbum.recover successfully');
} }
}); });
} }
``` ```
### recover
### getFileAssets recover(uri: string): Promise&lt;void&gt;;
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;;
Obtains file assets in the virtual album. This API uses a promise to return the result.
This is a system API. Recovers files in a system album.
**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT **Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO
> **NOTE**<br>
> The APL of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the ACL. For details, see [ACL](../../security/accesstoken-overview.md#acl).
>
> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ---------------------------------------- | ---- | -------------- | | -------- | ------------------------- | ---- | ---------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | Yes | Type of the media data to obtain. | | uri | string | Yes | Album URI.|
|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the files.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------------------- | ------------------------- | | --------------------------------------- | ----------------- |
| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| | Promise&lt;void&gt;| Promise that returns no value.|
**Example** **Example**
```ts ```ts
async function virtualAlbumGetFileAssetsDemoPromise() { import dataSharePredicates from '@ohos.data.dataSharePredicates';
console.info('virtualAlbumGetFileAssetsDemoPromise')
let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH);
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); async function example() {
let count = fetchResult.getCount(); console.info('privateAlbumRecoverDemoPromise');
console.info('fetchResult.count = ', count); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let predicates = new dataSharePredicates.DataSharePredicates();
let fetchOption = {
fetchColumns: [],
predicates: predicates
};
const trashAlbum = await albumList.getFirstObject();
let fetchResult = await trashAlbum.getPhotoAssets(fetchOption);
const fileAsset = await fetchResult.getFirstObject();
let recoverFileUri = fileAsset.uri;
trashAlbum.recover(recoverFileUri).then(() => {
console.info('trashAlbum.recover successfully');
}).catch((err) => {
console.info('trashAlbum.recover failed, message = ', err);
});
} }
``` ```
## MemberType
Enumerates the member types.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Type| Readable | Writable | Description |
| ----- | ---- | ---- | ---- | ---- |
| number | number | Yes| Yes| The member is a number.|
| string | string | Yes| Yes| The member is a string.|
| boolean | boolean | Yes| Yes| The member is a Boolean value.|
## ChangeEvent
Enumerates the type of changes to observe.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Type| Readable | Writable | Description|
| ----- | ---- | ---- | ---- | ---- |
| deviceChange | string | Yes| Yes| Device.|
| albumChange | string | Yes| Yes| Album.|
| imageChange | string | Yes| Yes| Image.|
| audioChange | string | Yes| Yes| Audio.|
| videoChange | string | Yes| Yes| Video.|
| remoteFileChange | string | Yes| Yes| Remote file.|
## PeerInfo ## PeerInfo
Describes information about a registered device. Defines information about a registered device.
This is a system API.
**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore
...@@ -2393,33 +2369,31 @@ This is a system API. ...@@ -2393,33 +2369,31 @@ This is a system API.
| networkId | string | Yes | No | Network ID of the registered device.| | networkId | string | Yes | No | Network ID of the registered device.|
| isOnline | boolean | Yes | No | Whether the registered device is online. | | isOnline | boolean | Yes | No | Whether the registered device is online. |
## MediaType
Enumerates the media types. ## FileType
Enumerates media file types.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Description| | Name | Value| Description|
| ----- | ---- | | ----- | ---- | ---- |
| FILE | File.| | IMAGE | 1 | Image.|
| IMAGE | Image.| | VIDEO | 2 | Video.|
| VIDEO | Video.| | AUDIO | 3 | Audio.|
| AUDIO | Audio.|
## FileKey ## PrivateAlbumType
Defines the key file information. Enumerates the system album types.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Default Value | Description | | Name | Value| Description |
| ------------- | ------------------- | ---------------------------------------------------------- | | ----- | ---- | ---- |
| URI | uri | File URI. | | TYPE_FAVORITE | 0 | Favorites.|
| RELATIVE_PATH | relative_path | Relative public directory of the file. | | TYPE_TRASH | 1 | Recycle bin.|
| DISPLAY_NAME | display_name | File name displayed. |
| 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 last modified. The value is the number of seconds elapsed since the Epoch time. |
| TITLE | title | Title in the file. |
## AudioKey ## AudioKey
...@@ -2427,10 +2401,9 @@ Defines the key information about an audio file. ...@@ -2427,10 +2401,9 @@ Defines the key information about an audio file.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- | | ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | Promise used to return the URI of the file created. | | URI | uri | File URI. |
| RELATIVE_PATH | relative_path | Relative public directory of the file. |
| DISPLAY_NAME | display_name | File name displayed. | | DISPLAY_NAME | display_name | File name displayed. |
| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | | 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 last modified. The value is the number of seconds elapsed since the Epoch time. | | DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. |
...@@ -2438,6 +2411,7 @@ Defines the key information about an audio file. ...@@ -2438,6 +2411,7 @@ Defines the key information about an audio file.
| ARTIST | artist | Author of the file. | | ARTIST | artist | Author of the file. |
| AUDIOALBUM | audio_album | Audio album. | | AUDIOALBUM | audio_album | Audio album. |
| DURATION | duration | Duration, in ms. | | DURATION | duration | Duration, in ms. |
| FAVORITE | favorite | Whether the file is added to favorites. |
## ImageVideoKey ## ImageVideoKey
...@@ -2445,17 +2419,20 @@ Defines the key information about an image or video file. ...@@ -2445,17 +2419,20 @@ Defines the key information about an image or video file.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- | | ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | File URI. | | URI | uri | File URI. |
| RELATIVE_PATH | relative_path | Relative public directory of the file. | | FILE_TYPE | file_type | Type of the file. |
| DISPLAY_NAME | display_name | File name displayed. | | DISPLAY_NAME | display_name | File name displayed. |
| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | | 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 last modified. The value is the number of seconds elapsed since the Epoch time. | | DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. |
| TITLE | title | Title in the file. |
| DURATION | duration | Duration, in ms. | | DURATION | duration | Duration, in ms. |
| WIDTH | width | Image width, in pixels. | | WIDTH | width | Image width, in pixels. |
| HEIGHT | height | Image height, in pixels. | | HEIGHT | height | Image height, in pixels. |
| DATE_TAKEN | date_taken | Date when the file (photo) was taken. 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. |
| ORIENTATION | orientation | Orientation of the image file. |
| FAVORITE | favorite | Whether the file is added to favorites. |
## AlbumKey ## AlbumKey
...@@ -2463,58 +2440,32 @@ Defines the key album information. ...@@ -2463,58 +2440,32 @@ Defines the key album information.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- | | ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | Album URI. | | URI | uri | Album URI. |
| RELATIVE_PATH | relative_path | Relative public directory of the album. | | FILE_TYPE | file_type | Type of the file. |
| DISPLAY_NAME | display_name | Album name displayed. | | ALBUM_NAME | album_name | Name of the album. |
| DATE_ADDED | date_added | Date when the album was added. The value is the number of seconds elapsed since the Epoch time. | | 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 album was last modified. The value is the number of seconds elapsed since the Epoch time. | | DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. |
## DirectoryType
Enumerates directory types.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Description |
| ------------- | ------------------ |
| DIR_CAMERA | Directory of camera files.|
| DIR_VIDEO | Directory of video files. |
| DIR_IMAGE | Directory of image files. |
| DIR_AUDIO | Directory of audio files. |
| DIR_DOCUMENTS | Directory of documents. |
| DIR_DOWNLOAD | Download directory. |
## MediaFetchOptions ## FetchOptions
Defines the options for fetching media files. Defines the options for fetching media files.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Type | Readable| Writable| Mandatory| Description | | Name | Type | Readable| Writable| Description |
| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | | ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ |
| selections | string | Yes | Yes | Yes | Conditions for fetching files. The values in [FileKey](#filekey) are used as the column names of the conditions. Example:<br>selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| | fetchColumns | Array&lt;string&gt; | Yes | Yes | Columns to fetch. If this parameter is left empty, data is fetched by URI, name, and file type by default. For example,<br>**fetchColumns: "uri"**.|
| selectionArgs | Array&lt;string&gt; | Yes | Yes | Yes | Values of the conditions specified in **selections**.<br>Example:<br>selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.|
## Size
Defines the image size.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | -------- |
| width | number | Yes | Yes | Image width, in pixels.|
| height | number | Yes | Yes | Image height, in pixels.|
## VirtualAlbumType ## AlbumFetchOptions
Enumerates the system or virtual album types.
This is a system API. Defines the options for fetching an album.
**System capability**: SystemCapability.FileManagement.UserFileManager.Core **System capability**: SystemCapability.FileManagement.UserFileManager.Core
| Name | Description | | Name | Type | Readable| Writable| Description |
| ------------- | ------------------ | | ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ |
| TYPE_FAVORITE | Favorites album.<br>This is a system API.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.|
| TYPE_TRASH | Trash album.<br>This is a system API.|
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册