HarmonyOS 鸿蒙Next PhotoViewPicker 返回的 photoUris 不能直接 fs.createStream

发布于 1周前 作者 eggper 来自 鸿蒙OS

HarmonyOS 鸿蒙Next PhotoViewPicker 返回的 photoUris 不能直接 fs.createStream

代码

uploadHeaderImage() {
let context = getContext(this) as common.Context; // 请确保 getContext(this) 返回结果为 UIAbilityContext
let photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 5;
let photoPicker = new picker.PhotoViewPicker(context);
photoPicker.select(photoSelectOptions).then(async (photoSelectResult: picker.PhotoSelectResult) => {
LogUtils.i('PhotoViewPicker.select successfully, photoSelectResult uri: ’ + JSON.stringify(photoSelectResult));
if (photoSelectResult && photoSelectResult.photoUris.length >= 1) {
this.userHeadImgUrl = photoSelectResult.photoUris[0];
const md5Str = await JFile.md5(photoSelectResult.photoUris[0]);
LogUtils.i(JFile.md5() :${md5Str});
} else {
ToastUtil.showToast(‘用户取消选择’);
}
}).catch((err: BusinessError) => {
console.error('PhotoViewPicker.select failed with err: ’ + JSON.stringify(err));
});
}

//md5方法

static async md5(filePath: string): Promise<string> {
let md: cryptoFramework.Md;
try {
md = cryptoFramework.createMd(‘MD5’);
} catch (e) {
LogUtils.d(‘md5 createMd with md5 fail:’ + JSON.stringify(e));
return ‘’;
}
try {
// let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
// LogUtils.i(md5 path=${file.path} fd=${file.fd} name=${file.name});
let context = getContext() as common.UIAbilityContext;
let atManager = abilityAccessCtrl.createAtManager();
await atManager.requestPermissionsFromUser(context, [‘ohos.permission.READ_MEDIA’,‘ohos.permission.READ_IMAGEVIDEO’]);
let inputStream = fs.createStreamSync(filePath, ‘r’);
let readLen = 256;
let readSize = 0;
while (readLen > 0) {
let buf = new ArrayBuffer(readLen);
readLen = await inputStream.read(buf, {
offset: readSize
});
if (readLen > 0) {
let inputDataBlob: cryptoFramework.DataBlob = {
data: new Uint8Array(buf, 0, readLen)
}
await md.update(inputDataBlob);
readSize += readLen;
}
}
let mdDigest = await md.digest();
// 使用TextDecoder转换为字符串
const textDecoder = new util.TextDecoder();
const md5Str = textDecoder.decodeWithStream(mdDigest.data);
return md5Str;
} catch (e) {
return ‘error:’ + JSON.stringify(e);
}

报错:

07-22 16:10:03.203   11421-11421  A03D00/JSAPP                   com.huifu…merchant  I     [picker] photo select result: {“resultCode”:0,“want”:{“deviceId”:"",“bundleName”:"",“abilityName”:"",“moduleName”:"",“uri”:"",“type”:"",“flags”:1,“action”:"",“parameters”:{“ability.params.stream”:[“file://media/Photo/19/IMG_1721371000_008/xihahou.jpg”],“isOriginal”:false,“moduleName”:"",“select-item-list”:[“file://media/Photo/19/IMG_1721371000_008/xihahou.jpg”]},“entities”:[]}}

07-22 16:10:03.203   11421-11421  A03D00/JSAPP                   com.huifu…merchant  I     [picker] photoSelectResult: {“data”:{“photoUris”:[“file://media/Photo/19/IMG_1721371000_008/xihahou.jpg”],“isOriginalPhoto”:false}}

07-22 16:10:03.203   11421-11421  A01111/hlmMerchantTag          com.huifu…merchant  I     PhotoViewPicker.select successfully, photoSelectResult uri: {“photoUris”:[“file://media/Photo/19/IMG_1721371000_008/xihahou.jpg”],“isOriginalPhoto”:false}

07-22 16:10:03.203   11421-11421  C05A01/NapiRequestPermission   com.huifu…merchant  I     [ParseRequestPermissionFromUser:690]asyncContext.uiAbilityFlag is: 1.

07-22 16:10:03.203   11421-11421  C05A02/CommonNapi              com.huifu…merchant  I     [ParseStringArray:139]array size is 2

07-22 16:10:03.203   11421-11421  C01331/AAFwkContext            com.huifu…merchant  I      [invalidDomain][ability_context_impl.cpp(OnAbilityResult:357)]OnAbilityResult

07-22 16:10:03.204   11421-12058  C05A01/NapiRequestPermission   com.huifu…merchant  I     [IsDynamicRequest:366]tokenID: 537777564.

07-22 16:10:03.206   11421-11456  C04207/WMSFocus                com.huifu…merchant  I     [window_session_impl.cpp] UpdateFocus<635>: Report update focus: 1, id: 401

07-22 16:10:03.210   11421-12058  C05A01/ATMProxy                com.huifu…merchant  I     [GetSelfPermissionsState:352]result from server data = 0

07-22 16:10:03.214   11421-12058  C05A01/NapiRequestPermission   com.huifu…merchant  I     [IsDynamicRequest:376]permission: ohos.permission.READ_MEDIA: state: 0

07-22 16:10:03.214   11421-12058  C05A01/NapiRequestPermission   com.huifu…merchant  I     [IsDynamicRequest:376]permission: ohos.permission.READ_IMAGEVIDEO: state: 0

07-22 16:10:03.214   11421-12058  C05A01/NapiRequestPermission   com.huifu…merchant  I     [RequestPermissionsFromUserExecute:731]it does not need to request permission

07-22 16:10:03.214   11421-11421  C04388/file_api                com.huifu…merchant  E     [create_stream.cpp:66->Sync] Failed to fdopen file by path

07-22 16:10:03.214   11421-11421  A01111/hlmMerchantTag          com.huifu…merchant  I     JFile.md5() :error:{“code”:13900002}

07-22 16:10:03.216   11421-11456  C03900/Ace                     com.huifu…merchant  I     [ui_content_impl.cpp(Focus)-(-1:100000:singleton)] [com.huifu.hlmmerchant][entry][100000]: window focus

4 回复

uri 可用 fs.open/openSync打开获取 File对象,然后 File.fd 句柄可用 fs.fdopenStream 获取流。

谢谢,可以读取了

图片能正常展示出来,无法读文件流

在HarmonyOS(鸿蒙系统)中,如果你遇到PhotoViewPicker组件返回的photoUris不能直接用于fs.createStream的问题,这通常是因为photoUris是图片的URI路径,而fs.createStream通常用于处理文件系统路径(如文件路径)。URI和文件系统路径在操作系统中是有区别的,URI可能指向设备上的任意位置,包括网络位置或特定应用的数据目录,而文件系统路径通常指的是设备本地存储中的具体位置。

为了解决这个问题,你需要先将URI指向的图片内容转换为可以本地访问的文件或数据流。在鸿蒙系统中,你可以使用MediaStore或相关的API来根据URI获取图片文件的实际路径(如果系统允许的话),或者使用MediaStore.Images.Media.openContentUri等方法直接打开URI对应的InputStream。然后,你可以使用这个InputStream来创建你需要的流,比如通过stream.pipe(fs.createWriteStream(localPath))将内容写入到本地文件,或者直接使用这个InputStream进行其他处理。

请注意,鸿蒙系统可能限制了对某些URI的直接访问,特别是在涉及安全和隐私保护的场景下。确保你的应用有适当的权限来访问这些资源。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部