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

!13378 modify medaiLibrary and userFIleManager

Merge pull request !13378 from 胡伟奇/modify_userFileManager
......@@ -54,7 +54,7 @@ globalThis.context.startAbilityForResult(
)
// FilePicker返回给startAbilityForResult的数据
var abilityResult = {
let abilityResult = {
resultCode: resultCode,
want: {
parameters: {
......
......@@ -42,8 +42,8 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE)
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE);
//myAlbum为新建文件保存路径,也是新建相册的名称
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) {
......@@ -80,7 +80,7 @@ async function example() {
selectionArgs: [],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0];
album.albumName = 'newAlbum';
......@@ -88,7 +88,7 @@ async function example() {
album.commitModify().then(function() {
console.info("albumRename successfully");
}).catch(function(err){
console.info("albumRename failed with error:"+ err);
console.info("albumRename failed with error: " + err);
});
}
```
......@@ -37,7 +37,7 @@ Openharmony上用户数据统一由媒体库进行管理,用户数据用户数
```ts
async function example(){
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') {
......@@ -80,11 +80,11 @@ OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线,
```ts
async function copyPublic2Sandbox() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
......@@ -107,7 +107,7 @@ async function copyPublic2Sandbox() {
```ts
async function copySandbox2Public() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
......@@ -119,26 +119,26 @@ async function copySandbox2Public() {
console.info('createFile failed, message = ' + err);
}
try {
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject();
} catch (err) {
console.info('file asset get failed, message = ', err)
console.info('file asset get failed, message = ' + err);
}
var fdPub = await fileAsset.open('rw');
var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
await fileio.copyFile(fdSand, fdPub);
await fileio.close(fdPub);
await fileio.close(fdSand);
let fdPubRead = await fileAsset.open('rw');
try {
var arrayBuffer = new ArrayBuffer(4096);
let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer));
var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead);
} catch (err) {
console.log('read text failed, message = ', err);
......@@ -166,12 +166,12 @@ async function copySandbox2Public() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) {
console.info("createAsset successfully:"+ JSON.stringify(asset));
console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){
console.info("createAsset failed with error:"+ err);
console.info("createAsset failed with error: " + err);
});
}
```
......@@ -191,10 +191,10 @@ async function copySandbox2Public() {
```ts
async function writeOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
......@@ -217,8 +217,8 @@ async function writeOnlyPromise() {
```ts
async function readOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
......@@ -232,7 +232,7 @@ async function readOnlyPromise() {
let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent
globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent);
await fileAsset.close(fd);
......
......@@ -21,7 +21,7 @@ MediaLibrary提供媒体库相关能力,帮助开发者更方便地访问和
> **说明:**<br/>
> 本开发指导基于API Version 9,仅适用于Stage模型。
应用需要先获取媒体库实例,才能访问和修改用户等个人媒体数据信息。媒体库涉及用户个人数据信息,所以应用需要向用户申请媒体库读写操作权限才能保证功能的正常运行。
应用需要先获取媒体库实例,才能访问和修改用户等个人媒体数据信息。媒体库涉及用户个人数据信息,所以应用需要向用户申请媒体库读写操作权限才能保证功能的正常运行。在使用媒体库相关接口时如无其他注明则默认在工程代码的pages/index.ets或者其他自创的ets文件中使用
开发者在使用MediaLibrary进行功能开发前,请先掌握以下内容:
......@@ -42,7 +42,7 @@ MediaLibrary提供媒体库相关能力,帮助开发者更方便地访问和
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
```
## 申请媒体库功能相关权限
......@@ -102,21 +102,21 @@ var media = mediaLibrary.getMediaLibrary(context);
}
```
2. 调用requestPermissionsFromUser进行权限校验,可以选择需要动态申请获取的权限。
2. 在Ability.ts中onWindowStageCreate里调用requestPermissionsFromUser进行权限校验,可以选择需要动态申请获取的权限自行添加相应代码
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA']
var permissionRequestResult;
let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
let permissionRequestResult;
let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, permissions, (err,result) => {
if(err){
atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err));
}else{
} else {
permissionRequestResult=result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
}
......@@ -125,4 +125,3 @@ var media = mediaLibrary.getMediaLibrary(context);
}
```
\ No newline at end of file
......@@ -33,14 +33,14 @@ selectionArgs: MediaType.IMAGE,媒体类型为图片。
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -64,13 +64,13 @@ selectionArgs:2022-8-5,具体添加时间的字符串。
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileKeyObj = mediaLibrary.FileKey;
let option = {
selections: fileKeyObj.DATE_ADDED + '= ?',
selectionArgs: ['2022-8-5'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -92,15 +92,15 @@ order: FileKey.DATE_ADDED,根据文件添加日期排序;并设置排列
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -124,14 +124,14 @@ selectionArgs:'myAlbum',具体相册名称。
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE;
let option = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs: ['myAlbum'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
......@@ -186,7 +186,7 @@ async function example() {
```ts
async function getCameraImagePromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
......@@ -235,7 +235,7 @@ async function getCameraImagePromise() {
```ts
async function getFirstThumbnailPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
......@@ -279,7 +279,7 @@ async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset));
......@@ -311,25 +311,25 @@ async function example() {
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
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;
}
//回调为空
asset.trash(true).then(() => {
console.info("trash successfully");
}).catch((err) => {
console.info("trash failed with error:"+ err);
console.info("trash failed with error: " + err);
});
}
```
......@@ -359,19 +359,19 @@ async function example() {
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let media = mediaLibrary.getMediaLibrary(context);
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;
}
asset.displayName = 'newImage.jpg';
//回调为空
......@@ -381,6 +381,6 @@ async function example() {
return;
}
console.log('fileRename successful.');
})
});
}
```
......@@ -202,7 +202,7 @@ on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------------------- |
| type | 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange' | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| type | 'deviceChange'&#124;<br/>'albumChange'&#124;<br/>'imageChange'&#124;<br/>'audioChange'&#124;<br/>'videoChange'&#124;<br/>'fileChange'&#124;<br/>'remoteFileChange' | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| callback | Callback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
......@@ -224,7 +224,7 @@ off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ---------------------------------------- |
| type | 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange' | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| type | 'deviceChange'&#124;<br/>'albumChange'&#124;<br/>'imageChange'&#124;<br/>'audioChange'&#124;<br/>'videoChange'&#124;<br/>'fileChange'&#124;<br/>'remoteFileChange' | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| callback | Callback&lt;void&gt; | 否 | 回调返回空 |
**示例:**
......
......@@ -37,6 +37,7 @@ getUserFileMgr(context: Context): UserFileManager
**示例:**
```ts
//此处获取的userFileManager实例mgr为全局对象,后续使用到mgr的地方默认为使用此处获取的对象,如未添加此段代码报mgr未定义的错误请自行添加
const context = getContext(this);
let mgr = userFileManager.getUserFileMgr(context);
```
......@@ -126,7 +127,7 @@ async function example() {
predicates: predicates
};
try {
var fetchResult = await mgr.getPhotoAssets(fetchOptions);
let fetchResult = await mgr.getPhotoAssets(fetchOptions);
if (fetchResult != undefined) {
console.info('fetchResult success');
let fileAsset = await fetchResult.getFirstObject();
......@@ -306,7 +307,7 @@ async function example() {
getPhotoAlbums(options: AlbumFetchOptions): Promise&lt;FetchResult&lt;Album&gt;&gt;;
获取相册,使用callback方式返回结果。
获取相册,使用Promise方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
......@@ -409,7 +410,7 @@ getPrivateAlbum(type: PrivateAlbumType): Promise&lt;FetchResult&lt;PrivateAlbum&
async function example() {
console.info('getPrivateAlbumDemo');
try {
var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let trashAlbum = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + trashAlbum.albumName);
} catch (err) {
......@@ -434,7 +435,7 @@ getAudioAssets(options: FetchOptions, callback: AsyncCallback&lt;FetchResult&lt;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------ | ---- | ------------------------- |
| options | [FetchOptions](#fetchoptions) | 是 | 检索选项 |
| callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | 是 | callback 返回相册检索结果 |
| callback | AsyncCallback&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | 是 | callback 返回音频检索结果 |
**示例:**
......@@ -484,7 +485,7 @@ getAudioAssets(options: FetchOptions): Promise&lt;FetchResult&lt;FileAsset&gt;&g
| 类型 | 说明 |
| --------------------------- | -------------- |
| Promise&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Promise 返回相册检索结果 |
| Promise&lt;[FetchResult](#fetchresult)&lt;[FileAsset](#fileasset)&gt;&gt; | Promise 返回音频检索结果 |
**示例:**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册