提交 d172cd6a 编写于 作者: G Gloria

Update docs against 14231+15161

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 8e88f87d
...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**. ...@@ -39,19 +39,19 @@ The following describes how to create an album named **myAlbum**.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album. // myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset === undefined) {
console.info('createAlbum successfully, message = ' + fileAsset); console.error('createAlbum failed, message = ' + err);
} else { } else {
console.info('createAlbum failed, message = ' + err); console.info('createAlbum successfully, message = ' + JSON.stringify(fileAsset));
} }
}); });
} }
``` ```
...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**. ...@@ -75,20 +75,20 @@ The following describes how to rename the album **newAlbum**.
```ts ```ts
async function example() { async function example() {
let AlbumNoArgsfetchOp = { let AlbumNoArgsfetchOp = {
selections: '', selections: '',
selectionArgs: [], selectionArgs: [],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
// Void callback. // Void callback.
album.commitModify().then(function() { album.commitModify().then(() => {
console.info("albumRename successfully"); console.info("albumRename successfully");
}).catch(function(err){ }).catch((err) => {
console.info("albumRename failed with error: " + err); console.error("albumRename failed with error: " + err);
}); });
} }
``` ```
...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi ...@@ -37,15 +37,15 @@ The following describes how to obtain the public directory that stores camera fi
```ts ```ts
async function example(){ async function example(){
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed'); console.info('mediaLibraryTest : getPublicDirectory passed');
} else { } else {
console.info('mediaLibraryTest : getPublicDirectory failed'); console.error('mediaLibraryTest : getPublicDirectory failed');
} }
} }
``` ```
...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli ...@@ -59,47 +59,52 @@ Users can access files stored in the public directories through the system appli
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. You can call [fs.open](../reference/apis/js-apis-file-fs.md#fsopen) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
- The **testFile.txt** file has been created and contains content.
**How to Develop** **How to Develop**
1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 1. Call [context.filesDir](../reference/apis/js-apis-file-fs.md) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox. 3. Call **fs.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory. 4. Call **fileAsset.open** to open the file in the public directory.
5. Call **fileio.copyfile** to copy the file. 5. Call [fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile) to copy the file.
6. Call **fileAsset.close** and **fileio.close** to close the file. 6. Call **fileAsset.close** and [fs.close](../reference/apis/js-apis-file-fs.md#fsclose) to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox** **Example 1: Copying Files from the Public Directory to the Sandbox**
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
try {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); let fdSand = await fs.open(sandboxDirPath + '/testFile.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
await fileio.copyFile(fdPub, fdSand); await fs.copyFile(fdPub, fdSand.fd);
await fileAsset.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); let content_sand = await fs.readText(sandboxDirPath + '/testFile.txt');
console.log('content read from sandbox file: ', content_sand) console.info('content read from sandbox file: ', content_sand)
} catch (err) {
console.info('[demo] copyPublic2Sandbox fail, err: ', err);
}
} }
``` ```
...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() { ...@@ -107,81 +112,81 @@ async function copyPublic2Sandbox() {
```ts ```ts
async function copySandbox2Public() { async function copySandbox2Public() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try { try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset); console.info('createFile successfully, message = ' + fileAsset);
} catch (err) { } catch (err) {
console.info('createFile failed, message = ' + err); console.error('createFile failed, message = ' + err);
} }
try { try {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'], selectionArgs: ['testFile02.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject(); var fileAsset = await fetchResult.getFirstObject();
} catch (err) { } catch (err) {
console.info('file asset get failed, message = ' + err); console.error('file asset get failed, message = ' + err);
} }
let fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); let fdSand = await fs.open(sandboxDirPath + 'testFile.txt', OpenMode.READ_WRITE);
await fileio.copyFile(fdSand, fdPub); await fs.copyFile(fdSand.fd, fdPub);
await fileio.close(fdPub); await fileAsset.close(fdPub);
await fileio.close(fdSand); await fs.close(fdSand.fd);
let fdPubRead = await fileAsset.open('rw'); let fdPubRead = await fileAsset.open('rw');
try { try {
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer); await fs.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer)); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead); fileAsset.close(fdPubRead);
} catch (err) { } catch (err) {
console.log('read text failed, message = ', err); console.error('read text failed, message = ', err);
} }
console.log('content read from public file: ', content_pub); console.info('content read from public file: ', content_pub);
} }
``` ```
### Reading and Writing a File ### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fs.read** and **fs.write** in [file.fs](../reference/apis/js-apis-file-fs.md) to read and write the file.
**Prerequisites** **Prerequisites**
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permissions **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. - You have imported the module [@ohos.file.fs](../reference/apis/js-apis-file-fs.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop** **How to Develop**
1. Create a file. 1. Create a file.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:" + JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){ }).catch((err) => {
console.info("createAsset failed with error: " + err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
2. Call **FileAsset.open** to open the file. 2. Call **FileAsset.open** to open the file.
3. Call **fileio.write** to write a string to the file. 3. Call [fs.write](../reference/apis/js-apis-file-fs.md#fswrite) to write a string to the file.
4. Call **fileio.read** to read the file and save the data read in an array buffer. 4. Call [fs.read](../reference/apis/js-apis-file-fs.md#fsread) to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string. 5. Convert the array buffer to a string.
...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -191,25 +196,25 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
```ts ```ts
async function writeOnlyPromise() { async function writeOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?', selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('w'); let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd); console.info('file descriptor: ', fd);
await fileio.write(fd, "Write file test content."); await fs.write(fd, "Write file test content.");
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('write file failed, message = ', err); console.error('write file failed, message = ', err);
} }
} }
``` ```
...@@ -217,28 +222,28 @@ async function writeOnlyPromise() { ...@@ -217,28 +222,28 @@ async function writeOnlyPromise() {
```ts ```ts
async function readOnlyPromise() { async function readOnlyPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName); console.info('fileAssetName: ', fileAsset.displayName);
try { try {
let fd = await fileAsset.open('r'); let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer); await fs.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent; globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName; globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent); console.info('file content: ', fileContent);
await fileAsset.close(fd); await fileAsset.close(fd);
} catch (err) { } catch (err) {
console.info('read file failed, message = ', err); console.error('read file failed, message = ', err);
} }
} }
``` ```
...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -64,64 +64,64 @@ After configuring the permissions in the **module.json5** file, the application
1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). 1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
```json ```json
{ {
"module": { "module": {
"requestPermissions": [ "requestPermissions": [
{ {
"name": "ohos.permission.MEDIA_LOCATION", "name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.READ_MEDIA", "name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
}, },
{ {
"name": "ohos.permission.WRITE_MEDIA", "name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"EntryAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
} }
] ]
} }
} }
``` ```
2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl'; import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA']; let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult; let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager(); let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, list, (err, result) => { atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) { if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
} else { } else {
permissionRequestResult=result; permissionRequestResult = result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
} }
}); });
} }
} }
``` ```
...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ...@@ -33,30 +33,33 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.log('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
### Querying Media Assets with the Specified Date ### Querying Media Assets with the Specified Date
The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ...@@ -64,23 +67,26 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let option = { let option = {
selections: fileKeyObj.DATE_ADDED + '= ?', selections: fileKeyObj.DATE_ADDED + '> ?',
selectionArgs: ['2022-8-5'], selectionArgs: ['2022-8-5'],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order** ...@@ -92,25 +98,28 @@ To sort files in descending order by the date when they are added, set **order**
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((fileAsset) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + fileAsset.displayName);
if (err) { for (let i = 1; i < fetchFileResult.getCount(); i++) {
console.error('Failed '); fetchFileResult.getNextObject().then((fileAsset) => {
return; console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
} }).catch((err) => {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.error('Failed to get next object: ' + err);
}) });
} }
}).catch((err) => {
console.error('Failed to get first object: ' + err);
});
} }
``` ```
...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ...@@ -124,31 +133,29 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE; let option = {
let option = { selections: fileKeyObj.ALBUM_NAME + '= ?',
selections: fileKeyObj.ALBUM_NAME + '= ?', selectionArgs: ['myAlbum'],
selectionArgs: ['myAlbum'], };
}; const context = getContext(this);
const context = getContext(this); let media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context); const fetchFileResult = await media.getFileAssets(option);
const fetchFileResult = await media.getFileAssets(option); if (albumList.length > 0) {
for (let i = 0; i < fetchFileResult.getCount(); i++) { fetchFileResult.getFirstObject().then((album) => {
fetchFileResult.getNextObject((err, fileAsset) => { console.info('getFirstObject.displayName : ' + album.albumName);
if (err) { }).catch((err) => {
console.error('Failed '); console.error('Failed to get first object: ' + err);
return; });
} } else {
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); console.info('getAlbum list is: 0');
}) }
}
} }
``` ```
## Obtaining Images and Videos in an Album ## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways: You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). - Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. - Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**. ...@@ -163,24 +170,24 @@ The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance. 1. Create a retrieval condition for obtaining the target **Album** instance.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
``` ```
2. Create a retrieval condition for obtaining videos in the target album. 2. Create a retrieval condition for obtaining videos in the target album.
```ts ```ts
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.VIDEO; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
``` ```
3. Call **Album.getFileAssets** to obtain the videos in the target album. 3. Call **Album.getFileAssets** to obtain the videos in the target album.
...@@ -188,28 +195,28 @@ Complete sample code: ...@@ -188,28 +195,28 @@ Complete sample code:
```ts ```ts
async function getCameraImagePromise() { async function getCameraImagePromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let videoType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = { let videoFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [videoType.toString()],
} }
let AlbumNoArgsFetchOp = { let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1'] selectionArgs:['New Album 1']
} }
let albumList = await media.getAlbums(AlbumNoArgsFetchOp); let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) { if (albumList.length > 0) {
const album = albumList[0]; const album = albumList[0];
let fetchFileResult = await album.getFileAssets(imagesFetchOp); let fetchFileResult = await album.getFileAssets(videoFetchOp);
let count = fetchFileResult.getCount(); let count = fetchFileResult.getCount();
console.info("get mediaLibrary IMAGE number", count); console.info("get mediaLibrary VIDEO number", count);
} else { } else {
console.info('getAlbum list is: 0'); console.info('getAlbum list is: 0');
} }
} }
``` ```
...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ...@@ -235,31 +242,32 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts ```ts
async function getFirstThumbnailPromise() { async function getFirstThumbnailPromise() {
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()], selectionArgs: [imageType.toString()],
} }
let size = { width: 720, height: 720 }; let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp); const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult != undefined) { if (fetchFileResult === undefined) {
const asset = await fetchFileResult.getFirstObject(); console.error("get image failed with error");
asset.getThumbnail(size).then((pixelMap) => { return;
pixelMap.getImageInfo().then((info) => { } else {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); const asset = await fetchFileResult.getFirstObject();
}).catch((err) => { asset.getThumbnail(size).then((pixelMap) => {
console.info("getImageInfo failed with error:" + err); pixelMap.getImageInfo().then((info) => {
}); console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => { }).catch((err) => {
console.info("getImageInfo failed with error:" + err); console.error("getImageInfo failed with error: " + err);
}); });
} else { }).catch((err) => {
console.info("get image failed with error"); console.error("getImageInfo failed with error: " + err);
} });
}
} }
``` ```
...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type. ...@@ -277,16 +285,16 @@ The following describes how to create a file of the **MediaType.FILE** type.
```ts ```ts
async function example() { async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => { media.createAsset(mediaType, "testFile.text", path).then((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => { }).catch((err) => {
console.info("createAsset failed with error:"+ err); console.error("createAsset failed with error: " + err);
}); });
} }
``` ```
...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy ...@@ -312,26 +320,26 @@ The following describes how to move the first file in the result set to the recy
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return; return;
} }
// Void callback. // Void callback.
asset.trash(true).then(() => { asset.trash(true).then(() => {
console.info("trash successfully"); console.info("trash successfully");
}).catch((err) => { }).catch((err) => {
console.info("trash failed with error: " + err); console.error("trash failed with error: " + err);
}); });
} }
``` ```
...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch ...@@ -346,7 +354,7 @@ Before renaming a file, you must obtain the file, for example, by calling [Fetch
- You have obtained a **MediaLibrary** instance. - You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**. - You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the first file in the result set as **newtitle.text**. The following describes how to rename the first file in the result set as **newImage.jpg**.
**How to Develop** **How to Develop**
...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,28 +366,28 @@ The following describes how to rename the first file in the result set as **newt
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE; let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
let media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset === undefined) {
console.error('asset not exist'); console.error('asset not exist');
return;
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return; return;
} }
asset.displayName = 'newImage.jpg'; console.info('fileRename successful.');
// Void callback. });
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.log('fileRename successful.');
});
} }
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册