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

!14231 file-management log abarbeitung

Merge pull request !14231 from 胡伟奇/file-management
...@@ -46,10 +46,10 @@ async function example() { ...@@ -46,10 +46,10 @@ async function example() {
const path = await media.getPublicDirectory(DIR_IMAGE); const path = await media.getPublicDirectory(DIR_IMAGE);
//myAlbum为新建文件保存路径,也是新建相册的名称 //myAlbum为新建文件保存路径,也是新建相册的名称
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));
} }
}); });
} }
...@@ -85,10 +85,10 @@ async function example() { ...@@ -85,10 +85,10 @@ async function example() {
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
//回调返回空 //回调返回空
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);
}); });
} }
``` ```
...@@ -30,7 +30,7 @@ Openharmony上用户数据统一由媒体库进行管理,用户数据用户数 ...@@ -30,7 +30,7 @@ Openharmony上用户数据统一由媒体库进行管理,用户数据用户数
**前提条件** **前提条件**
- 获取媒体库mediaLibrary实例。 - 获取媒体库mediaLibrary实例。
- 申请媒体库读权限“ohos.permission.READ_MEDIA - 申请媒体库读权限"ohos.permission.READ_MEDIA"
下面以获取Camera文件保存的公共目录为例。 下面以获取Camera文件保存的公共目录为例。
...@@ -43,7 +43,7 @@ async function example(){ ...@@ -43,7 +43,7 @@ async function example(){
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');
} }
} }
``` ```
...@@ -58,47 +58,52 @@ OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线, ...@@ -58,47 +58,52 @@ OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线,
通过接口[mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1)可以打开公共路径文件。 通过接口[mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1)可以打开公共路径文件。
通过接口[fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7)可以打开沙箱路径文件,沙箱路径必须通过应用上下文context进行访问。 通过接口[fs.open](../reference/apis/js-apis-file-fs.md#fsopen)可以打开沙箱路径文件,沙箱路径必须通过应用上下文context进行访问。
**前提条件** **前提条件**
- 获取媒体库mediaLibrary实例。 - 获取媒体库mediaLibrary实例。
- 申请媒体库读写权限“ohos.permission.WRITE_MEDIA。 - 申请媒体库读写权限"ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA"。
- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.fileio](../reference/apis/js-apis-fileio.md) - 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.file.fs](../reference/apis/js-apis-file-fs.md)
- 测试文件 "testFile.txt" 已创建且有文件内容。
**开发步骤** **开发步骤**
1. 调用[context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir)获取应用沙箱路径。 1. 调用[context.filesDir](../reference/apis/js-apis-file-fs.md)获取应用沙箱路径。
2. 调用MediaLibrary.getFileAssets和FetchFileResult.getFirstObject获取公共目录中的FileAsset实例。 2. 调用MediaLibrary.getFileAssets和FetchFileResult.getFirstObject获取公共目录中的FileAsset实例。
3. 调用fileio.open打开沙箱路径文件。 3. 调用fs.open打开沙箱路径文件。
4. 调用fileAsset.open打开公共路径文件。 4. 调用fileAsset.open打开公共路径文件。
5. 调用fileio.copyfile复制文件。 5. 调用[fs.copyfile](../reference/apis/js-apis-file-fs.md#fscopyfile)复制文件。
6. 调用fileAsset.close和fileio.close关闭文件。 6. 调用fileAsset.close和[fs.close](../reference/apis/js-apis-file-fs.md#fsclose)关闭文件。
**示例1 将公共路径文件复制到沙箱路径下** **示例1 将公共路径文件复制到沙箱路径下**
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
const context = getContext(this); try {
let media = mediaLibrary.getMediaLibrary(context); const context = getContext(this);
let sandboxDirPath = globalThis.context.filesDir; let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let sandboxDirPath = context.filesDir;
let fileAssetFetchOp = { let fileKeyObj = mediaLibrary.FileKey;
selections: fileKeyObj.DISPLAY_NAME + '= ?', let fileAssetFetchOp = {
selectionArgs: ['testFile.txt'], selections: fileKeyObj.DISPLAY_NAME + '= ?',
}; selectionArgs: ['testFile.txt'],
let fetchResult = await media.getFileAssets(fileAssetFetchOp); };
let fileAsset = await fetchResult.getFirstObject(); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
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);
}
} }
``` ```
...@@ -108,7 +113,7 @@ async function copyPublic2Sandbox() { ...@@ -108,7 +113,7 @@ async function copyPublic2Sandbox() {
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);
...@@ -116,7 +121,7 @@ async function copySandbox2Public() { ...@@ -116,7 +121,7 @@ async function copySandbox2Public() {
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;
...@@ -127,35 +132,35 @@ async function copySandbox2Public() { ...@@ -127,35 +132,35 @@ async function copySandbox2Public() {
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);
} }
``` ```
### 读写文件内容 ### 读写文件内容
通过[mediaLibrary](../reference/apis/js-apis-medialibrary.md)的接口FileAsset.open和FileAsset.close可以打开和关闭文件。通过[fileio](../reference/apis/js-apis-fileio.md)的接口fileio.read和fileio.write可以读写文件。 通过[mediaLibrary](../reference/apis/js-apis-medialibrary.md)的接口FileAsset.open和FileAsset.close可以打开和关闭文件。通过[file.fs](../reference/apis/js-apis-file-fs.md)中的接口fs.read和fs.write可以读写文件。
**前提条件** **前提条件**
- 获取媒体库mediaLibrary实例。 - 获取媒体库mediaLibrary实例。
- 申请媒体库读写权限“ohos.permission.WRITE_MEDIA - 申请媒体库读写权限"ohos.permission.READ_MEDIA, ohos.permission.WRITE_MEDIA"
- 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.fileio](../reference/apis/js-apis-fileio.md) - 除了@ohos.multimedia.mediaLibrary外,还需要导入模块[@ohos.file.fs](../reference/apis/js-apis-file-fs.md)
**开发步骤** **开发步骤**
...@@ -168,19 +173,19 @@ async function copySandbox2Public() { ...@@ -168,19 +173,19 @@ async function copySandbox2Public() {
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. 使用open打开文件。 2. 使用open打开文件。
3. 使用fileio.write写入文件,以string形式传入写入数据。 3. 使用[fs.write](../reference/apis/js-apis-file-fs.md#fswrite)写入文件,以string形式传入写入数据。
4. 使用fileio.read读取文件,以 ArrayBuffer 形式保存读取结果。 4. 使用[fs.read](../reference/apis/js-apis-file-fs.md#fsread)读取文件,以 ArrayBuffer 形式保存读取结果。
5. 将ArrayBuffer转化为string,以string形式得到文件内容。 5. 将ArrayBuffer转化为string,以string形式得到文件内容。
...@@ -204,10 +209,10 @@ async function writeOnlyPromise() { ...@@ -204,10 +209,10 @@ async function writeOnlyPromise() {
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);
} }
} }
``` ```
...@@ -230,14 +235,14 @@ async function readOnlyPromise() { ...@@ -230,14 +235,14 @@ async function readOnlyPromise() {
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);
} }
} }
``` ```
......
...@@ -109,19 +109,19 @@ let media = mediaLibrary.getMediaLibrary(context); ...@@ -109,19 +109,19 @@ let media = mediaLibrary.getMediaLibrary(context);
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));
} }
}); });
} }
} }
``` ```
...@@ -42,21 +42,24 @@ async function example() { ...@@ -42,21 +42,24 @@ async function example() {
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.error('Failed to get next object: ' + err);
});
} }
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); }).catch((err) => {
}) console.error('Failed to get first object: ' + err);
} });
} }
``` ```
### 指定日期 ### 指定日期
下面以查询指定添加日期媒体资源为例。实际开发中可以设置添加日期、修改日期、拍摄日期。 下面以查询指定添加日期至今的所有媒体资源为例。实际开发中可以设置添加日期、修改日期、拍摄日期。
selections: FileKey.DATE_ADDED,根据文件添加日期检索。 selections: FileKey.DATE_ADDED,根据文件添加日期检索。
...@@ -66,21 +69,24 @@ selectionArgs:2022-8-5,具体添加时间的字符串。 ...@@ -66,21 +69,24 @@ selectionArgs:2022-8-5,具体添加时间的字符串。
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.error('Failed to get next object: ' + err);
});
} }
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); }).catch((err) => {
}) console.error('Failed to get first object: ' + err);
} });
} }
``` ```
...@@ -102,15 +108,18 @@ async function example() { ...@@ -102,15 +108,18 @@ async function example() {
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.error('Failed to get next object: ' + err);
});
} }
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); }).catch((err) => {
}) console.error('Failed to get first object: ' + err);
} });
} }
``` ```
...@@ -133,15 +142,15 @@ async function example() { ...@@ -133,15 +142,15 @@ async function example() {
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++) { if (albumList.length > 0) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getFirstObject().then((album) => {
if (err) { console.info('getFirstObject.displayName : ' + album.albumName);
console.error('Failed '); }).catch((err) => {
return; console.error('Failed to get first object: ' + err);
} });
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); } else {
}) console.info('getAlbum list is: 0');
} }
} }
``` ```
...@@ -172,10 +181,10 @@ async function example() { ...@@ -172,10 +181,10 @@ async function example() {
```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()],
} }
``` ```
...@@ -188,10 +197,10 @@ async function getCameraImagePromise() { ...@@ -188,10 +197,10 @@ 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 + '= ?',
...@@ -201,9 +210,9 @@ async function getCameraImagePromise() { ...@@ -201,9 +210,9 @@ async function getCameraImagePromise() {
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');
} }
...@@ -245,19 +254,20 @@ async function getFirstThumbnailPromise() { ...@@ -245,19 +254,20 @@ async function getFirstThumbnailPromise() {
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) {
console.error("get image failed with error");
return;
} else {
const asset = await fetchFileResult.getFirstObject(); const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size).then((pixelMap) => { asset.getThumbnail(size).then((pixelMap) => {
pixelMap.getImageInfo().then((info) => { pixelMap.getImageInfo().then((info) => {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); 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);
}); });
}).catch((err) => { }).catch((err) => {
console.info("getImageInfo failed with error:" + err); console.error("getImageInfo failed with error: " + err);
}); });
} else {
console.info("get image failed with error");
} }
} }
``` ```
...@@ -281,10 +291,10 @@ async function example() { ...@@ -281,10 +291,10 @@ async function example() {
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);
}); });
} }
``` ```
...@@ -321,15 +331,15 @@ async function example() { ...@@ -321,15 +331,15 @@ async function example() {
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;
} }
//回调为空 //回调为空
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);
}); });
} }
``` ```
...@@ -347,7 +357,7 @@ async function example() { ...@@ -347,7 +357,7 @@ async function example() {
- 获取媒体库mediaLibrary实例。 - 获取媒体库mediaLibrary实例。
- 申请媒体库读写权限“ohos.permission.WRITE_MEDIA”。 - 申请媒体库读写权限“ohos.permission.WRITE_MEDIA”。
下面以将文件检索结果中第一个文件重命名为“newtitle.text”为例。 下面以将文件检索结果中第一个文件重命名为“newImage.jpg”为例。
**开发步骤** **开发步骤**
...@@ -360,7 +370,7 @@ async function example() { ...@@ -360,7 +370,7 @@ async function example() {
```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()],
...@@ -369,18 +379,18 @@ async function example() { ...@@ -369,18 +379,18 @@ async function example() {
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;
} }
asset.displayName = 'newImage.jpg'; asset.displayName = 'newImage.jpg';
//回调为空 //回调为空
asset.commitModify((err) => { asset.commitModify((err) => {
if (err) { if (err) {
console.error('fileRename Failed '); console.error('fileRename Failed ');
return; return;
} }
console.log('fileRename successful.'); console.info('fileRename successful.');
}); });
} }
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册