diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md
index 0b0b8964a6bafc9bb57b923b261a018194c13203..752de65c1cb3089d882ca922587c05e2455a56f7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md
@@ -1,6 +1,6 @@
# @ohos.multimedia.medialibrary (媒体库管理)
->  **说明:**
+> **说明:**
> 该组件从API Version 6开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 导入模块
@@ -33,6 +33,7 @@ getMediaLibrary(context: Context): MediaLibrary
**示例:(从API Version 9开始)**
```ts
+// 获取mediaLibrary实例,后续用到此实例均采用此处获取的实例
const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context);
```
@@ -91,46 +92,59 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileRe
**示例:**
```js
-let fileKeyObj = mediaLibrary.FileKey;
-let imageType = mediaLibrary.MediaType.IMAGE;
-let imagesFetchOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
-};
-media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
- if (fetchFileResult == undefined) {
- console.error('Failed to get fetchFileResult: ' + error);
- return;
- }
- const count = fetchFileResult.getCount();
- if (count < 0) {
- console.error('Failed to get count from fetchFileResult: count: ' + count);
- return;
- }
- if (count == 0) {
- console.info('The count of fetchFileResult is zero');
- return;
- }
-
- console.info('Get fetchFileResult success, count: ' + count);
- fetchFileResult.getFirstObject((err, fileAsset) => {
- if (fileAsset == undefined) {
- console.error('Failed to get first object: ' + err);
+async function example() {
+ let fileKeyObj = mediaLibrary.FileKey;
+ let imageType = mediaLibrary.MediaType.IMAGE;
+ // 创建文件获取选项,此处参数为获取image类型的文件资源
+ let imagesFetchOp = {
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ };
+ // 获取文件资源,使用callback方式返回异步结果
+ media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => {
+ // 判断获取的文件资源的检索结果集是否为undefined,若为undefined则接口调用失败
+ if (fetchFileResult == undefined) {
+ console.error('get fetchFileResult failed with error: ' + error);
return;
}
- console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName);
- for (let i = 1; i < count; i++) {
- fetchFileResult.getNextObject((err, fileAsset) => {
- if (fileAsset == undefined) {
- console.error('Failed to get next object: ' + err);
- return;
- }
- console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
- })
+ // 获取文件检索结果集中的总数
+ const count = fetchFileResult.getCount();
+ // 判断结果集中的数量是否小于0,小于0时表示接口调用失败
+ if (count < 0) {
+ console.error('get count from fetchFileResult failed, count: ' + count);
+ return;
}
+ // 判断结果集中的数量是否等于0,等于0时表示接口调用成功,但是检索结果集为空,请检查文件获取选项参数配置是否有误和设备中是否存在相应文件
+ if (count == 0) {
+ console.info('The count of fetchFileResult is zero');
+ return;
+ }
+ console.info('Get fetchFileResult successfully, count: ' + count);
+ // 获取文件检索结果集中的第一个资源,使用callback方式返回异步结果
+ fetchFileResult.getFirstObject((error, fileAsset) => {
+ // 检查获取的第一个资源是否为undefined,若为undefined则接口调用失败
+ if (fileAsset == undefined) {
+ console.error('get first object failed with error: ' + error);
+ return;
+ }
+ console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
+ // 调用 getNextObject 接口获取下一个资源,直到最后一个
+ for (let i = 1; i < count; i++) {
+ fetchFileResult.getNextObject((error, fileAsset) => {
+ if (fileAsset == undefined) {
+ console.error('get next object failed with error: ' + error);
+ return;
+ }
+ console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
+ })
+ }
+ });
+ // 释放FetchFileResult实例并使其失效。无法调用其他方法
+ fetchFileResult.close();
});
-});
+}
```
+
### getFileAssets7+
getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult>
@@ -156,38 +170,51 @@ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult>
**示例:**
```js
-let fileKeyObj = mediaLibrary.FileKey;
-let imageType = mediaLibrary.MediaType.IMAGE;
-let imagesFetchOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
-};
-media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
- const count = fetchFileResult.getCount();
- if (count < 0) {
- console.error('Failed to get count from fetchFileResult: count: ' + count);
- return;
- }
- if (count == 0) {
- console.info('The count of fetchFileResult is zero');
- return;
- }
- console.info('Get fetchFileResult success, count: ' + count);
- fetchFileResult.getFirstObject().then(function(fileAsset) {
- console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName);
- for (let i = 1; i < count; i++) {
- fetchFileResult.getNextObject().then(function(fileAsset) {
- console.info('fileAsset.displayName ' + ': ' + fileAsset.displayName);
- }).catch(function(err) {
- console.error('Failed to get next object: ' + err);
- })
+async function example() {
+ let fileKeyObj = mediaLibrary.FileKey;
+ let imageType = mediaLibrary.MediaType.IMAGE;
+ // 创建文件获取选项,此处参数为获取image类型的文件资源
+ let imagesFetchOp = {
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ };
+ // 获取文件资源,使用Promise方式返回结果
+ media.getFileAssets(imagesFetchOp).then((fetchFileResult) => {
+ // 获取文件检索结果集中的总数
+ const count = fetchFileResult.getCount();
+ // 判断结果集中的数量是否小于0,小于0时表示接口调用失败
+ if (count < 0) {
+ console.error('get count from fetchFileResult failed, count: ' + count);
+ return;
}
- }).catch(function(err) {
- console.error('Failed to get first object: ' + err);
+ // 判断结果集中的数量是否等于0,等于0时表示接口调用成功,但是检索结果集为空,请检查文件获取选项参数配置是否有误和设备中是否存在相应文件
+ if (count == 0) {
+ console.info('The count of fetchFileResult is zero');
+ return;
+ }
+ console.info('Get fetchFileResult successfully, count: ' + count);
+ // 获取文件检索结果集中的第一个资源,使用Promise方式返回异步结果
+ fetchFileResult.getFirstObject().then((fileAsset) => {
+ console.info('fileAsset.displayName ' + '0 : ' + fileAsset.displayName);
+ // 调用 getNextObject 接口获取下一个资源,直到最后一个
+ for (let i = 1; i < count; i++) {
+ fetchFileResult.getNextObject().then((fileAsset) => {
+ console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('get next object failed with error: ' + error);
+ })
+ }
+ }).catch((error) => {
+ // 调用getFirstObject接口失败
+ console.error('get first object failed with error: ' + error);
+ });
+ // 释放FetchFileResult实例并使其失效。无法调用其他方法
+ fetchFileResult.close();
+ }).catch((error) => {
+ // 调用getFileAssets接口失败
+ console.error('get file assets failed with error: ' + error);
});
-}).catch(function(err){
- console.error("Failed to get file assets: " + err);
-});
+}
```
### on8+
@@ -231,7 +258,7 @@ off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange
```js
media.off('imageChange', () => {
- // stop listening success
+ // stop listening successfully
})
```
@@ -262,11 +289,11 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => {
+ media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (error, fileAsset) => {
if (fileAsset != undefined) {
console.info('createAsset successfully, message');
} else {
- console.error('createAsset failed, message = ' + err);
+ console.error('createAsset failed with error: ' + error);
}
});
}
@@ -306,8 +333,8 @@ async function example() {
const path = await media.getPublicDirectory(DIR_IMAGE);
media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => {
console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset));
- }).catch((err) => {
- console.error('createAsset failed, message = ' + err);
+ }).catch((error) => {
+ console.error('createAsset failed with error: ' + error);
});
}
```
@@ -348,14 +375,15 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
- console.error('asset not exist')
- return
+ console.error('asset not exist');
+ return;
}
media.deleteAsset(asset.uri).then(() => {
- console.info("deleteAsset successfully");
- }).catch((err) => {
- console.error("deleteAsset failed with error:"+ err);
+ console.info('deleteAsset successfully');
+ }).catch((error) => {
+ console.error('deleteAsset failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -390,16 +418,17 @@ async function example() {
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
- console.error('asset not exist')
- return
+ console.error('asset not exist');
+ return;
}
- media.deleteAsset(asset.uri, (err) => {
- if (err != undefined) {
- console.info("deleteAsset successfully");
+ media.deleteAsset(asset.uri, (error) => {
+ if (error != undefined) {
+ console.error('deleteAsset failed with error: ' + error);
} else {
- console.error("deleteAsset failed with error:"+ err);
+ console.info('deleteAsset successfully');
}
});
+ fetchFileResult.close();
}
```
@@ -422,11 +451,11 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>):
```js
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
-media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => {
+media.getPublicDirectory(DIR_CAMERA, (error, dicResult) => {
if (dicResult == 'Camera/') {
- console.info('mediaLibraryTest : getPublicDirectory passed');
+ console.info('getPublicDirectory DIR_CAMERA successfully');
} else {
- console.error('mediaLibraryTest : getPublicDirectory failed');
+ console.error('getPublicDirectory DIR_CAMERA failed with error: ' + error);
}
});
```
@@ -456,12 +485,15 @@ getPublicDirectory(type: DirectoryType): Promise<string>
```js
async function example() {
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
- const dicResult = await media.getPublicDirectory(DIR_CAMERA);
- if (dicResult == 'Camera/') {
- console.info('MediaLibraryTest : getPublicDirectory');
- } else {
- console.error('MediaLibraryTest : getPublicDirectory failed');
- }
+ media.getPublicDirectory(DIR_CAMERA).then((dicResult) => {
+ if (dicResult == 'Camera/') {
+ console.info('getPublicDirectory DIR_CAMERA successfully');
+ } else {
+ console.error('getPublicDirectory DIR_CAMERA failed');
+ }
+ }).catch((error) => {
+ console.error('getPublicDirectory failed with error: ' + error);
+ });
}
```
@@ -485,19 +517,19 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback {
- if (albumList != undefined) {
- const album = albumList[0];
- console.info('album.albumName = ' + album.albumName);
- console.info('album.count = ' + album.count);
- } else {
- console.error('getAlbum fail, message = ' + err);
- }
-})
+async function example() {
+ let AlbumNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
+ };
+ media.getAlbums(AlbumNoArgsfetchOp, (error, albumList) => {
+ if (albumList != undefined) {
+ console.info('getAlbums successfully: ' + JSON.stringify(albumList));
+ } else {
+ console.error('getAlbums failed with error: ' + error);
+ }
+ })
+}
```
### getAlbums7+
@@ -525,15 +557,17 @@ getAlbums(options: MediaFetchOptions): Promise
**示例:**
```js
-let AlbumNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
-};
-media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){
- console.info("getAlbums successfully:"+ JSON.stringify(albumList));
-}).catch(function(err){
- console.error("getAlbums failed with error: " + err);
-});
+async function example() {
+ let AlbumNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
+ };
+ media.getAlbums(AlbumNoArgsfetchOp).then((albumList) => {
+ console.info('getAlbums successfully: ' + JSON.stringify(albumList));
+ }).catch((error) => {
+ console.error('getAlbums failed with error: ' + error);
+ });
+}
```
### release8+
@@ -549,12 +583,12 @@ release(callback: AsyncCallback<void>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------- |
-| callback | AsyncCallback<void> | 是 | 回调表示成功还是失败 |
+| callback | AsyncCallback<void> | 是 | 无返回值 |
**示例:**
```js
-media.release((err) => {
+media.release(() => {
// do something
});
```
@@ -601,16 +635,16 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>)
```js
let option = {
- src : "/data/storage/el2/base/haps/entry/image.png",
- mimeType : "image/*",
- relativePath : "Pictures/"
+ src : '/data/storage/el2/base/haps/entry/image.png',
+ mimeType : 'image/*',
+ relativePath : 'Pictures/'
};
-mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => {
- if (err) {
- console.error("An error occurred when storing media resources.");
+mediaLibrary.getMediaLibrary().storeMediaAsset(option, (error, value) => {
+ if (error) {
+ console.error('storeMediaAsset failed with error: ' + error);
return;
}
- console.info("Media resources stored. ");
+ console.info('Media resources stored. ');
// Obtain the URI that stores media resources.
});
```
@@ -642,15 +676,15 @@ storeMediaAsset(option: MediaAssetOption): Promise<string>
```js
let option = {
- src : "/data/storage/el2/base/haps/entry/image.png",
- mimeType : "image/*",
- relativePath : "Pictures/"
+ src : '/data/storage/el2/base/haps/entry/image.png',
+ mimeType : 'image/*',
+ relativePath : 'Pictures/'
};
mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => {
- console.info("Media resources stored.");
+ console.info('Media resources stored.');
// Obtain the URI that stores media resources.
-}).catch((err) => {
- console.error("An error occurred when storing media resources.");
+}).catch((error) => {
+ console.error('storeMediaAsset failed with error: ' + error);
});
```
@@ -669,7 +703,7 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 |
+| images | Array<string> | 是 | 预览的图片URI('https://','datashare://')列表。 |
| index | number | 是 | 开始显示的图片序号。 |
| callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 |
@@ -677,22 +711,22 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* 网络图片使用方式
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
let index = 1;
-mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => {
- if (err) {
- console.error("An error occurred when previewing the images.");
+mediaLibrary.getMediaLibrary().startImagePreview(images, index, (error) => {
+ if (error) {
+ console.error('startImagePreview failed with error: ' + error);
return;
}
- console.info("Succeeded in previewing the images.");
+ console.info('Succeeded in previewing the images.');
});
```
@@ -711,28 +745,28 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 |
+| images | Array<string> | 是 | 预览的图片URI('https://','datashare://')列表。 |
| callback | AsyncCallback<void> | 是 | 图片预览回调,失败时返回错误信息。 |
**示例:**
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* 网络图片使用方式
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
-mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => {
- if (err) {
- console.error("An error occurred when previewing the images.");
+mediaLibrary.getMediaLibrary().startImagePreview(images, (error) => {
+ if (error) {
+ console.error('startImagePreview failed with error: ' + error);
return;
}
- console.info("Succeeded in previewing the images.");
+ console.info('Succeeded in previewing the images.');
});
```
@@ -751,7 +785,7 @@ startImagePreview(images: Array<string>, index?: number): Promise<void&
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | ---------------------------------------- |
-| images | Array<string> | 是 | 预览的图片URI("https://","datashare://")列表。 |
+| images | Array<string> | 是 | 预览的图片URI('https://','datashare://')列表。 |
| index | number | 否 | 开始显示的图片序号,不选择时默认为0。 |
**返回值:**
@@ -764,20 +798,20 @@ startImagePreview(images: Array<string>, index?: number): Promise<void&
```js
let images = [
- "datashare:///media/xxxx/2",
- "datashare:///media/xxxx/3"
+ 'datashare:///media/xxxx/2',
+ 'datashare:///media/xxxx/3'
];
/* 网络图片使用方式
let images = [
- "https://media.xxxx.com/image1.jpg",
- "https://media.xxxx.com/image2.jpg"
+ 'https://media.xxxx.com/image1.jpg',
+ 'https://media.xxxx.com/image2.jpg'
];
*/
let index = 1;
mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => {
- console.info("Succeeded in previewing the images.");
-}).catch((err) => {
- console.error("An error occurred when previewing the images.");
+ console.info('Succeeded in previewing the images.');
+}).catch((error) => {
+ console.error('startImagePreview failed with error: ' + error);
});
```
@@ -803,15 +837,15 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array<
```js
let option : mediaLibrary.MediaSelectOption = {
- type : "media",
+ type : 'media',
count : 2
};
-mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => {
- if (err) {
- console.error("An error occurred when selecting media resources.");
+mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, value) => {
+ if (error) {
+ console.error('startMediaSelect failed with error: ' + error);
return;
}
- console.info("Media resources selected.");
+ console.info('Media resources selected.');
// Obtain the media selection value.
});
```
@@ -843,14 +877,14 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>>
```js
let option : mediaLibrary.MediaSelectOption = {
- type : "media",
+ type : 'media',
count : 2
};
mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
- console.info("Media resources selected.");
+ console.info('Media resources selected.');
// Obtain the media selection value.
-}).catch((err) => {
- console.error("An error occurred when selecting media resources.");
+}).catch((error) => {
+ console.error('startMediaSelect failed with error: ' + error);
});
```
@@ -878,14 +912,12 @@ getActivePeers(): Promise\>;
async function example() {
media.getActivePeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.info('get distributed info is undefined!')
+ console.info('get distributed info is undefined!');
}
- }).catch((err) => {
- console.error("get distributed info failed with error:" + err);
+ }).catch((error) => {
+ console.error('get distributed info failed with error: ' + error);
});
}
```
@@ -912,15 +944,13 @@ getActivePeers(callback: AsyncCallback\>): void;
```js
async function example() {
- media.getActivePeers((err, devicesInfo) => {
+ media.getActivePeers((error, devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.error('get distributed fail, message = ' + err)
+ console.error('get distributed failed with error: ' + error);
}
- })
+ });
}
```
@@ -949,14 +979,12 @@ getAllPeers(): Promise\>;
async function example() {
media.getAllPeers().then((devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.info('get distributed info is undefined!')
+ console.info('get distributed info is undefined!');
}
- }).catch((err) => {
- console.error("get distributed info failed with error: " + err);
+ }).catch((error) => {
+ console.error('get distributed info failed with error: ' + error);
});
}
```
@@ -983,15 +1011,13 @@ getAllPeers(callback: AsyncCallback\>): void;
```js
async function example() {
- media.getAllPeers((err, devicesInfo) => {
+ media.getAllPeers((error, devicesInfo) => {
if (devicesInfo != undefined) {
- for (let i = 0; i < devicesInfo.length; i++) {
- console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
- }
+ console.info('get distributed info ' + JSON.stringify(devicesInfo));
} else {
- console.error('get distributed fail, message = ' + err)
+ console.error('get distributed failed with error: ' + error);
}
- })
+ });
}
```
@@ -999,7 +1025,7 @@ async function example() {
提供封装文件属性的方法。
->  **说明:**
+> **说明:**
> 1. title字段默认为去掉后缀的文件名,音频和视频文件会尝试解析文件内容,部分设备写入后在触发扫描时会被还原。
> 2. orientation字段部分设备可能不支持修改,建议使用image组件的[ModifyImageProperty](js-apis-image.md#modifyimageproperty9)接口。
@@ -1052,19 +1078,23 @@ isDirectory(callback: AsyncCallback<boolean>): void
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isDirectory((err, isDirectory) => {
- // do something
+ asset.isDirectory((error, isDirectory) => {
+ if (error) {
+ console.error('isDirectory failed with error: ' + error);
+ } else {
+ console.info('isDirectory result:' + isDirectory);
+ }
});
+ fetchFileResult.close();
}
```
@@ -1088,21 +1118,21 @@ isDirectory():Promise<boolean>
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isDirectory().then(function(isDirectory){
- console.info("isDirectory result:"+ isDirectory);
- }).catch(function(err){
- console.error("isDirectory failed with error: " + err);
+ asset.isDirectory().then((isDirectory) => {
+ console.info('isDirectory result:' + isDirectory);
+ }).catch((error) => {
+ console.error('isDirectory failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1126,20 +1156,20 @@ commitModify(callback: AsyncCallback<void>): void
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
asset.commitModify(() => {
- console.info('commitModify success');
+ console.info('commitModify successfully');
});
+ fetchFileResult.close();
}
```
@@ -1163,18 +1193,18 @@ commitModify(): Promise<void>
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
- asset.commitModify();
+ await asset.commitModify();
+ fetchFileResult.close();
}
```
@@ -1184,7 +1214,7 @@ open(mode: string, callback: AsyncCallback<number>): void
打开当前文件,使用callback方式返回异步结果。
-**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放
+**注意**:以 'w' 模式打开文件时,返回的fd无法进行读取。但由于不同文件系统实现上的差异,部分用户态文件系统在 'w' 模式打开时会允许用fd读取。若有针对fd的读写行为,建议使用 'rw' 模式打开文件。当前写操作是互斥的操作,写操作完成后需要调用close进行释放。
**需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1204,13 +1234,13 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- const asset = await media.createAsset(mediaType, "image00003.jpg", path);
- asset.open('rw', (openError, fd) => {
- if(fd > 0){
- asset.close(fd);
- }else{
- console.error('File Open Failed!' + openError);
- }
+ const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
+ asset.open('rw', (error, fd) => {
+ if (fd > 0) {
+ asset.close(fd);
+ } else {
+ console.error('File Open failed with error: ' + error);
+ }
});
}
```
@@ -1221,7 +1251,7 @@ open(mode: string): Promise<number>
打开当前文件,使用promise方式返回异步结果。
-**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放
+**注意**:以 'w' 模式打开文件时,返回的fd无法进行读取。但由于不同文件系统实现上的差异,部分用户态文件系统在 'w' 模式打开时会允许用fd读取。若有针对fd的读写行为,建议使用 'rw' 模式打开文件。当前写操作是互斥的操作,写操作完成后需要调用close进行释放。
**需要权限**:ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
@@ -1246,14 +1276,12 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const path = await media.getPublicDirectory(DIR_IMAGE);
- const asset = await media.createAsset(mediaType, "image00003.jpg", path);
- asset.open('rw')
- .then((fd) => {
- console.info('File fd!' + fd);
- })
- .catch((err) => {
- console.error('File err!' + err);
- });
+ const asset = await media.createAsset(mediaType, 'image00003.jpg', path);
+ asset.open('rw').then((fd) => {
+ console.info('File open fd: ' + fd);
+ }).catch((error) => {
+ console.error('File open failed with error: ' + error);
+ });
}
```
@@ -1278,30 +1306,28 @@ close(fd: number, callback: AsyncCallback<void>): void
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
- console.info('File fd!' + fd);
- asset.close(fd, (closeErr) => {
- if (closeErr != undefined) {
- console.error('mediaLibraryTest : close : FAIL ' + closeErr);
- console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL');
+ console.info('File open fd: ' + fd);
+ asset.close(fd, (error) => {
+ if (error) {
+ console.error('asset.close failed with error: ' + error);
} else {
- console.info("=======asset.close success====>");
+ console.info('asset.close successfully');
}
});
- })
- .catch((err) => {
- console.error('File err!' + err);
+ }).catch((error) => {
+ console.error('File open failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1331,31 +1357,26 @@ close(fd: number): Promise<void>
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
console.info('File fd!' + fd);
- asset.close(fd).then((closeErr) => {
- if (closeErr != undefined) {
- console.error('mediaLibraryTest : close : FAIL ' + closeErr);
- console.error('mediaLibraryTest : ASSET_CALLBACK : FAIL');
-
- } else {
- console.info("=======asset.close success====>");
- }
+ asset.close(fd).then(() => {
+ console.info('asset.close successfully');
+ }).catch((closeErr) => {
+ console.error('asset.close fail, closeErr: ' + closeErr);
});
- })
- .catch((err) => {
- console.error('File err!' + err);
+ }).catch((error) => {
+ console.error('open File failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1379,19 +1400,23 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void
```js
async function example() {
- let fileKeyObj = mediaLibrary.FileKey
+ let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
- selections: fileKeyObj.MEDIA_TYPE + '= ?',
- selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail((err, pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
+ asset.getThumbnail((error, pixelmap) => {
+ if (error) {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }
});
+ fetchFileResult.close();
}
```
@@ -1419,17 +1444,21 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail(size, (err, pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
+ asset.getThumbnail(size, (error, pixelmap) => {
+ if (error) {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }
});
+ fetchFileResult.close();
}
```
@@ -1464,19 +1493,17 @@ async function example() {
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.getThumbnail(size)
- .then((pixelmap) => {
- console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap);
- })
- .catch((err) => {
- console.error('mediaLibraryTest : getThumbnail fail, err: ' + err);
+ asset.getThumbnail(size).then((pixelmap) => {
+ console.info('mediaLibrary getThumbnail Successful, pixelmap ' + JSON.stringify(pixelmap));
+ }).catch((error) => {
+ console.error('mediaLibrary getThumbnail failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1504,16 +1531,20 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.favorite(true,function(err){
- // do something
+ asset.favorite(true,(error) => {
+ if (error) {
+ console.error('mediaLibrary favorite failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary favorite Successful');
+ }
});
+ fetchFileResult.close();
}
```
@@ -1546,18 +1577,18 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.favorite(true).then(function() {
- console.info("favorite successfully");
- }).catch(function(err){
- console.error("favorite failed with error: " + err);
+ asset.favorite(true).then(() => {
+ console.info('mediaLibrary favorite Successful');
+ }).catch((error) => {
+ console.error('mediaLibrary favorite failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1584,20 +1615,20 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isFavorite((err, isFavorite) => {
- if (isFavorite) {
- console.info('FileAsset is favorite');
- }else{
- console.info('FileAsset is not favorite');
+ asset.isFavorite((error, isFavorite) => {
+ if (error) {
+ console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
}
});
+ fetchFileResult.close();
}
```
@@ -1624,18 +1655,18 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isFavorite().then(function(isFavorite){
- console.info("isFavorite result:"+ isFavorite);
- }).catch(function(err){
- console.error("isFavorite failed with error: " + err);
+ asset.isFavorite().then((isFavorite) => {
+ console.info('mediaLibrary isFavorite Successful, isFavorite result: ' + isFavorite);
+ }).catch((error) => {
+ console.error('mediaLibrary favoriisFavoritete failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1665,17 +1696,20 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.trash(true, trashCallBack);
- function trashCallBack(err, trash) {
- console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash');
- }
+ asset.trash(true, (error) => {
+ if (error) {
+ console.error('mediaLibrary trash failed with error: ' + error);
+ } else {
+ console.info('mediaLibrary trash Successful');
+ }
+ });
+ fetchFileResult.close();
}
```
@@ -1710,18 +1744,18 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.trash(true).then(function() {
- console.info("trash successfully");
- }).catch(function(err){
- console.error("trash failed with error: " + err);
+ asset.trash(true).then(() => {
+ console.info('trash successfully');
+ }).catch((error) => {
+ console.error('trash failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1748,20 +1782,20 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isTrash((err, isTrash) => {
- if (isTrash == undefined) {
- console.error('Failed to get trash state: ' + err);
- return;
- }
- console.info('Get trash state success: ' + isTrash);
+ asset.isTrash((error, isTrash) => {
+ if (error) {
+ console.error('Failed to get trash state failed with error: ' + error);
+ return;
+ }
+ console.info('Get trash state successfully, isTrash result: ' + isTrash);
});
+ fetchFileResult.close();
}
```
@@ -1788,17 +1822,18 @@ 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",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
const fetchFileResult = await media.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
- asset.isTrash().then(function(isTrash){
- console.info("isTrash result: " + isTrash);
- }).catch(function(err){
- console.error("isTrash failed with error: " + err);
+ asset.isTrash().then((isTrash) => {
+ console.info('isTrash result: ' + isTrash);
+ }).catch((error) => {
+ console.error('isTrash failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1829,11 +1864,12 @@ async function example() {
let getFileCountOneOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
- order: fileKeyObj.DATE_ADDED + " DESC",
- extendArgs: "",
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getFileCountOneOp);
const fetchCount = fetchFileResult.getCount();
+ console.info('fetchCount result: ' + fetchCount);
+ fetchFileResult.close();
}
```
@@ -1858,25 +1894,22 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount();
- console.info('mediaLibraryTest : count:' + fetchCount);
+ console.info('mediaLibrary fetchFileResult.getCount, count:' + fetchCount);
let fileAsset = await fetchFileResult.getFirstObject();
for (var i = 1; i < fetchCount; i++) {
- fileAsset = await fetchFileResult.getNextObject();
- if(i == fetchCount - 1) {
- console.info('mediaLibraryTest : isLast');
- var result = fetchFileResult.isAfterLast();
- console.info('mediaLibraryTest : isAfterLast:' + result);
- console.info('mediaLibraryTest : isAfterLast end');
- fetchFileResult.close();
- }
+ fileAsset = await fetchFileResult.getNextObject();
+ if(i == fetchCount - 1) {
+ var result = fetchFileResult.isAfterLast();
+ console.info('mediaLibrary fileAsset isAfterLast result: ' + result);
+ }
}
+ fetchFileResult.close();
}
```
@@ -1895,10 +1928,9 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
fetchFileResult.close();
@@ -1926,19 +1958,19 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getFirstObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getFirstObject((error, fileAsset) => {
+ if (error) {
+ console.error('fetchFileResult getFirstObject failed with error: ' + error);
+ return;
+ }
+ console.info('getFirstObject successfully, displayName : ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -1963,17 +1995,17 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getFirstObject().then(function(fileAsset){
- console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset));
- }).catch(function(err){
- console.error("getFirstObject failed with error: " + err);
+ fetchFileResult.getFirstObject().then((fileAsset) => {
+ console.info('getFirstObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getFirstObject failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -1981,7 +2013,9 @@ async function example() {
getNextObject(callback: AsyncCallback<FileAsset>): void
-获取文件检索结果中的下一个文件资产。此方法使用callback形式返回结果。
+获取文件检索结果中的下一个文件资产,此方法使用callback形式返回结果。
+
+> **说明**: 在使用前需要先使用[getFirstObject](#getfirstobject7)接口获取第一个文件资产,然后使用[isAfterLast](#isafterlast7)确认文件检索集当前不是指向最后一个时方可使用此接口。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
@@ -1998,20 +2032,24 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getNextObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.log('fileAsset.displayName : ' + fileAsset.displayName);
- })
+ let fileAsset = await fetchFileResult.getFirstObject();
+ if (!fetchFileResult.isAfterLast) {
+ fetchFileResult.getNextObject((error, fileAsset) => {
+ if (error) {
+ console.error('fetchFileResult getNextObject failed with error: ' + error);
+ return;
+ }
+ console.log('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
+ })
+ }
+ fetchFileResult.close();
}
+
```
### getNextObject7+
@@ -2020,6 +2058,8 @@ async function example() {
获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。
+> **说明**: 在使用前需要先使用[getFirstObject](#getfirstobject7)接口获取第一个文件资产,然后使用[isAfterLast](#isafterlast7)确认文件检索集当前不是指向最后一个时方可使用此接口。
+
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**返回值**:
@@ -2035,15 +2075,20 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- const fetchCount = fetchFileResult.getCount();
- console.info('mediaLibraryTest : count:' + fetchCount);
- let fileAsset = await fetchFileResult.getNextObject();
+ let fileAsset = await fetchFileResult.getFirstObject();
+ if (!fetchFileResult.isAfterLast) {
+ fetchFileResult.getNextObject().then((fileAsset) => {
+ console.info('fetchFileResult getNextObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('fetchFileResult getNextObject failed with error: ' + error);
+ })
+ }
+ fetchFileResult.close();
}
```
@@ -2068,19 +2113,19 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getLastObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getLastObject((error, fileAsset) => {
+ if (error) {
+ console.error('getLastObject failed with error: ' + error);
+ return;
+ }
+ console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -2105,13 +2150,17 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- let lastObject = await fetchFileResult.getLastObject();
+ fetchFileResult.getLastObject().then((fileAsset) => {
+ console.info('getLastObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getLastObject failed with error: ' + error);
+ });
+ fetchFileResult.close();
}
```
@@ -2127,7 +2176,7 @@ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------ |
-| index | number | 是 | 要获取的文件的索引,从0开始 |
+| index | number | 是 | 要获取的文件的索引,从0开始(注意该值要小于文件检索集的count值) |
| callback | AsyncCallback<[FileAsset](#fileasset7)> | 是 | 异步返回FileAsset之后的回调 |
**示例**:
@@ -2137,19 +2186,19 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getPositionObject(0, (err, fileAsset) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ fetchFileResult.getPositionObject(0, (error, fileAsset) => {
+ if (error) {
+ console.error('getPositionObject failed with error: ' + error);
+ return;
+ }
+ console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
})
+ fetchFileResult.close();
}
```
@@ -2165,7 +2214,7 @@ getPositionObject(index: number): Promise<FileAsset>
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ------ | ---- | -------------- |
-| index | number | 是 | 要获取的文件的索引,从0开始 |
+| index | number | 是 | 要获取的文件的索引,从0开始(注意该值要小于文件检索集的count值) |
**返回值**:
@@ -2180,17 +2229,17 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getPositionObject(1) .then(function (fileAsset){
- console.info('fileAsset.displayName : ' + fileAsset.displayName);
- }).catch(function (err) {
- console.error("getFileAssets failed with error: " + err);
+ fetchFileResult.getPositionObject(0).then((fileAsset) => {
+ console.info('getPositionObject successfully, displayName: ' + fileAsset.displayName);
+ }).catch((error) => {
+ console.error('getPositionObject failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -2206,7 +2255,7 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | -------------------- |
-| callback | AsyncCallback> | 是 | 异步返回FileAsset列表之后的回调 |
+| callback | AsyncCallback<Array<[FileAsset](#fileasset7)>> | 是 | 异步返回FileAsset列表之后的回调 |
**示例**:
@@ -2215,21 +2264,21 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- fetchFileResult.getAllObject((err, fileAsset) => {
- if (err) {
- console.error('Failed ');
+ fetchFileResult.getAllObject((error, fileAssetList) => {
+ if (error) {
+ console.error('getAllObject failed with error: ' + error);
return;
}
for (let i = 0; i < fetchFileResult.getCount(); i++) {
- console.info('fileAsset.displayName : ' + fileAsset[i].displayName);
+ console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
}
})
+ fetchFileResult.close();
}
```
@@ -2245,7 +2294,7 @@ getAllObject(): Promise<Array<FileAsset>>
| 类型 | 说明 |
| ---------------------------------------- | --------------------- |
-| Promise> | 返回FileAsset对象列表 |
+| Promise<Array<[FileAsset](#fileasset7)>> | 返回FileAsset对象列表 |
**示例**:
@@ -2254,13 +2303,19 @@ 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: "",
+ selections: fileKeyObj.MEDIA_TYPE + '= ?',
+ selectionArgs: [imageType.toString()],
+ order: fileKeyObj.DATE_ADDED + ' DESC',
};
let fetchFileResult = await media.getFileAssets(getImageOp);
- var data = fetchFileResult.getAllObject();
+ fetchFileResult.getAllObject().then((fileAssetList) => {
+ for (let i = 0; i < fetchFileResult.getCount(); i++) {
+ console.info('getAllObject fileAssetList ' + i + ' displayName: ' + fileAssetList[i].displayName);
+ }
+ }).catch((error) => {
+ console.error('getAllObject failed with error: ' + error);
+ });
+ fetchFileResult.close();
}
```
@@ -2309,12 +2364,12 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
album.albumName = 'hello';
- album.commitModify((err) => {
- if (err) {
- console.error('Failed ');
- return;
- }
- console.info('Modify successful.');
+ album.commitModify((error) => {
+ if (error) {
+ console.error('commitModify failed with error: ' + error);
+ return;
+ }
+ console.info('commitModify successful.');
})
}
```
@@ -2346,10 +2401,10 @@ async function example() {
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
album.albumName = 'hello';
- album.commitModify().then(function() {
- console.info("commitModify successfully");
- }).catch(function(err){
- console.error("commitModify failed with error: " + err);
+ album.commitModify().then(() => {
+ console.info('commitModify successfully');
+ }).catch((error) => {
+ console.error('commitModify failed with error: ' + error);
});
}
```
@@ -2380,15 +2435,22 @@ async function example() {
selectionArgs: [],
};
let fileNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
+ selections: '',
+ selectionArgs: [],
}
+ // 获取符合检索要求的相册,返回相册列表
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
- album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack);
- function getFileAssetsCallBack(err, fetchFileResult) {
- // do something
- }
+ // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源
+ album.getFileAssets(fileNoArgsfetchOp, (error, fetchFileResult) => {
+ if (error) {
+ console.error('album getFileAssets failed with error: ' + error);
+ return;
+ }
+ let count = fetchFileResult.getcount();
+ console.info('album getFileAssets successfully, count: ' + count);
+ });
+ fetchFileResult.close();
}
```
@@ -2422,17 +2484,21 @@ async function example() {
selections: '',
selectionArgs: [],
};
- let fileNoArgsfetchOp = {
- selections: '',
- selectionArgs: [],
+ let fileNoArgsfetchOp = {
+ selections: '',
+ selectionArgs: [],
};
+ // 获取符合检索要求的相册,返回相册列表
const albumList = await media.getAlbums(AlbumNoArgsfetchOp);
const album = albumList[0];
- album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){
- console.info("getFileAssets successfully: " + JSON.stringify(albumFetchFileResult));
- }).catch(function(err){
- console.error("getFileAssets failed with error: " + err);
+ // 取到相册列表中的一个相册,获取此相册中所有符合媒体检索选项的媒体资源
+ album.getFileAssets(fileNoArgsfetchOp).then((albumFetchFileResult) => {
+ let count = fetchFileResult.getcount();
+ console.info('album getFileAssets successfully, count: ' + count);
+ }).catch((error) => {
+ console.error('album getFileAssets failed with error: ' + error);
});
+ fetchFileResult.close();
}
```
@@ -2470,32 +2536,32 @@ async function example() {
枚举,文件关键信息。
->  **说明:**
+> **说明:**
> bucket_id字段在文件重命名或移动后可能会发生变化,开发者使用前需要重新获取。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.MediaLibrary.Core
| 名称 | 值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- |
-| ID | "file_id" | 文件编号 |
-| RELATIVE_PATH | "relative_path" | 相对公共目录路径 |
-| DISPLAY_NAME | "display_name" | 显示名字 |
-| PARENT | "parent" | 父目录id |
-| MIME_TYPE | "mime_type" | 文件扩展属性 |
-| MEDIA_TYPE | "media_type" | 媒体类型 |
-| SIZE | "size" | 文件大小(单位:字节) |
-| DATE_ADDED | "date_added" | 添加日期(添加文件时间到1970年1月1日的秒数值) |
-| DATE_MODIFIED | "date_modified" | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) |
-| DATE_TAKEN | "date_taken" | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) |
-| TITLE | "title" | 文件标题 |
-| ARTIST | "artist" | 作者 |
-| AUDIOALBUM | "audio_album" | 专辑 |
-| DURATION | "duration" | 持续时间(单位:毫秒) |
-| WIDTH | "width" | 图片宽度(单位:像素) |
-| HEIGHT | "height" | 图片高度(单位:像素) |
-| ORIENTATION | "orientation" | 图片显示方向,即顺时针旋转角度,如0,90,180。(单位:度) |
-| ALBUM_ID | "bucket_id" | 文件所归属的相册编号 |
-| ALBUM_NAME | "bucket_display_name" | 文件所归属相册名称 |
+| ID | 'file_id' | 文件编号 |
+| RELATIVE_PATH | 'relative_path' | 相对公共目录路径 |
+| DISPLAY_NAME | 'display_name' | 显示名字 |
+| PARENT | 'parent' | 父目录id |
+| MIME_TYPE | 'mime_type' | 文件扩展属性(如:image/*、video/*、file/*) |
+| MEDIA_TYPE | 'media_type' | 媒体类型 |
+| SIZE | 'size' | 文件大小(单位:字节) |
+| DATE_ADDED | 'date_added' | 添加日期(添加文件时间到1970年1月1日的秒数值) |
+| DATE_MODIFIED | 'date_modified' | 修改日期(修改文件时间到1970年1月1日的秒数值,修改文件名不会改变此值,当文件内容发生修改时才会更新) |
+| DATE_TAKEN | 'date_taken' | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) |
+| TITLE | 'title' | 文件标题 |
+| ARTIST | 'artist' | 作者 |
+| AUDIOALBUM | 'audio_album' | 专辑 |
+| DURATION | 'duration' | 持续时间(单位:毫秒) |
+| WIDTH | 'width' | 图片宽度(单位:像素) |
+| HEIGHT | 'height' | 图片高度(单位:像素) |
+| ORIENTATION | 'orientation' | 图片显示方向,即顺时针旋转角度,如0,90,180。(单位:度) |
+| ALBUM_ID | 'bucket_id' | 文件所归属的相册编号 |
+| ALBUM_NAME | 'bucket_display_name' | 文件所归属相册名称 |
## DirectoryType8+
@@ -2538,9 +2604,9 @@ async function example() {
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------------- | ------------------- | ---- | ---- | ------------------------------------------------------------ |
-| selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
+| selections | string | 是 | 是 | 检索条件,使用[FileKey](#filekey8)中的枚举值作为检索条件的列名。示例:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' + mediaLibrary.FileKey.MEDIA_TYPE + '= ?', |
| selectionArgs | Array<string> | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。
示例:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
-| order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" |
+| order | string | 是 | 是 | 检索结果排序方式,使用[FileKey](#filekey8)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:
升序排列:order: mediaLibrary.FileKey.DATE_ADDED + ' ASC'
降序排列:order: mediaLibrary.FileKey.DATE_ADDED + ' DESC' |
| uri8+ | string | 是 | 是 | 文件URI |
| networkId8+ | string | 是 | 是 | 注册设备网络ID |
| extendArgs8+ | string | 是 | 是 | 扩展的检索参数,目前没有扩展检索参数 |
@@ -2584,4 +2650,3 @@ async function example() {
| type | 'image' | 'video' | 'media' | 是 | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 |
| count | number | 是 | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 |
-