HarmonyOS 鸿蒙Next ohos.permission.WRITE_IMAGEVIDEO等图片视频存储权限问题以及具体实现功能的详细代码
HarmonyOS 鸿蒙Next ohos.permission.WRITE_IMAGEVIDEO等图片视频存储权限问题以及具体实现功能的详细代码
1. 目前需要存储图片和视频,是否一定要支持ACL权限
2. imageVideo权限是不是需要签名?多次无法build启动
3. 文件: 图、视频的同步存储和相册存储,能否提供下具体的实现代码
- 目前需要存储图片和视频,是否一定要支持ACL权限
答复:不需要,ACL权限只有符合场景才可以申请,其他场景下无法使用 2. imageVideo权限是不是需要签名?多次无法build启动
答复:需要配置profile文件的权限 3. 文件: 图、视频的同步存储和相册存储,能否提供下具体的实现代码
答复:1楼的方案是savebutton方式,如果不喜欢该按钮可以使用showAssetsCreationDialog(不需要使用ACL权限)
import { common } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'
import fs from '@ohos.file.fs';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileUri } from '@kit.CoreFileKit';
import { buffer } from '@kit.ArkTS';
export function myRawfileCopy(context: common.UIAbilityContext) {
context.resourceManager.getRawFileContent("background.png", (err: BusinessError, data: Uint8Array) => {
if (err != null) {
console.error(`open aaa.txt failed: ${err.message}`)
} else {
let buffer = data.buffer
let sanboxPath = context.filesDir
console.log('myRawfileCopy path' + sanboxPath)
let file = fs.openSync(context.filesDir + '/test.png', fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
try {
fs.writeSync(file.fd, buffer) // 拷贝文件到沙箱,为了简便,这里是直接getrawfilecontent然后写入,当文件过大时内存压力会很大,如需优化,可通过buffer进行读取
fs.close(file.fd)
} catch (err) {
console.log('myRawfileCopy error')
}
}
})
}
let context = getContext(this);
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
async function example(context: common.UIAbilityContext) {
console.info('ShowAssetsCreationDialogDemo.');
try {
// 获取需要保存到媒体库的位于应用沙箱的图片/视频uri
let srcFileUris: Array<string> = [
fileUri.getUriFromPath(context.filesDir+ '/test.png')
];
let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
{
title: 'test2', // 可选
fileNameExtension: 'png',
photoType: photoAccessHelper.PhotoType.IMAGE,
subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
}
];
let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
let file1 = fs.openSync(context.filesDir+ '/test.png', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let arrayBuffer = new ArrayBuffer(4096000);
let readLen = fs.readSync(file1.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(`content of File: ${buf.toString()}`);
let file2 = fs.openSync(desFileUris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let writeLen = fs.writeSync(file2.fd, arrayBuffer);
fs.closeSync(file2);
fs.closeSync(file1);
console.info('showAssetsCreationDialog success, data is ' + desFileUris);
} catch (err) {
console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
}
}
@Component
@Entry
struct Index {
build() {
Column() {
Button('拷贝文件到沙箱').onClick(() => {
myRawfileCopy(getContext(this) as common.UIAbilityContext)
})
Button('保存到').onClick(() => {
example(getContext(this) as common.UIAbilityContext)
})
}
}
}
更多关于HarmonyOS 鸿蒙Next ohos.permission.WRITE_IMAGEVIDEO等图片视频存储权限问题以及具体实现功能的详细代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
IMAGEVIDEO权限需要acl申请后才可以使用,权限列表及申请流程请查看此文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-signing-0000001587684945-V5#section9786111152213 若您只是要下载图片或者视频到应用沙箱目录则只要ohos.permission.INTERNET网络权限就行,https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#requestdownloadfile9-1
获取图片资源getAssets的替代方案是使用PhotoViewPicker.select方法获取临时权限 同样createAsset写入也可以使用安全控件SaveButton来替代使用
import { abilityAccessCtrl, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { http } from '@kit.NetworkKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State saveButtonOptions: SaveButtonOptions = {
icon: SaveIconStyle.FULL_FILLED,
text: SaveDescription.SAVE_IMAGE,
buttonType: ButtonType.Capsule
} // 设置安全控件按钮属性
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
SaveButton().onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result == SaveButtonOnClickResult.SUCCESS) {
let url = 'xxx'
let ctx = getContext(this) as common.UIAbilityContext;
console.log("开始加载=======")
http.createHttp().request(
url,
{
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
expectDataType: 2
},
async (error: BusinessError, data: http.HttpResponse) => {
console.log('================data', JSON.stringify(data));
if (error) {
console.error(`http request failed with. Code: ${error.code}`, error.message);
} else {
if (200 === data.responseCode) {
console.log("result:", data.result)
let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
try {
// 获取相册路径
let helper = photoAccessHelper.getPhotoAccessHelper(ctx);
// let uri = await helper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4');
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 写入文件
await fs.write(file.fd, imageBuffer);
// 关闭文件
await fs.close(file.fd);
console.log("操作成功")
} catch (e) {
console.error('文件操作失败', e.message);
}
}
}
}
)
}
})
}
.width('100%')
}
.height('100%')
}
}
在HarmonyOS鸿蒙系统中,针对ohos.permission.WRITE_IMAGEVIDEO
等图片视频存储权限问题,具体实现功能通常涉及以下几个步骤:
-
权限声明:在
config.json
文件中声明所需权限,例如:"module": { "package": "com.example.myapp", "reqPermissions": [ "ohos.permission.WRITE_IMAGEVIDEO" ] }
-
请求权限:在应用启动时或需要存储图片视频时,向用户请求权限。可以使用
Ability
的requestPermissionsFromUser
方法:List<String> permissions = new ArrayList<>(); permissions.add("ohos.permission.WRITE_IMAGEVIDEO"); requestPermissionsFromUser(permissions, 1);
-
权限处理:在回调中处理权限请求结果,判断是否已授权:
[@Override](/user/Override) public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == IPermissionManager.PERMISSION_GRANT) { // 已授权,执行存储图片视频操作 } else { // 未授权,处理相应逻辑 } } }
-
存储操作:使用文件IO操作进行图片视频的存储。
请注意,上述代码片段未展示完整的文件存储实现,仅描述了权限请求流程。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html