HarmonyOS鸿蒙Next中使用showAssetsCreationDialog获取权限uri保存网络图片问题
HarmonyOS鸿蒙Next中使用showAssetsCreationDialog获取权限uri保存网络图片问题 网络图片下载到沙箱,在调用showAssetsCreationDialog,但是提示401
沙箱路径 ${context.cacheDir}_${fileName} 放入 srcFileUris 申请报401,请问有大佬懂吗?

更多关于HarmonyOS鸿蒙Next中使用showAssetsCreationDialog获取权限uri保存网络图片问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html



没搞懂沙箱文件为啥不对
更多关于HarmonyOS鸿蒙Next中使用showAssetsCreationDialog获取权限uri保存网络图片问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
这个路沙箱文件径是接口返回的还是自己拼接的?
srcFileUris能打印出来看下不,保存到沙箱时应该会有一个URI返回的
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'png')
另外下载网络图片并保存可以参考下这个: https://gitee.com/scenario-samples/my-application-save-image
在HarmonyOS鸿蒙Next中,showAssetsCreationDialog用于获取用户选择的URI权限,以便保存网络图片。具体步骤如下:
-
调用
showAssetsCreationDialog方法:该方法会弹出一个对话框,提示用户选择保存图片的位置。用户选择后,系统会返回一个URI。 -
获取URI:通过
showAssetsCreationDialog返回的URI,可以获取用户选择的保存路径。 -
保存网络图片:使用获取的URI,通过
File或OutputStream等类将网络图片保存到指定位置。
示例代码:
import file from '@ohos.file';
import request from '@ohos.request';
async function saveImageFromUrl(imageUrl: string) {
try {
// 获取用户选择的URI
const uri = await file.showAssetsCreationDialog();
// 下载网络图片
const response = await request.downloadFile(imageUrl, uri);
if (response.code === 0) {
console.log('图片保存成功');
} else {
console.error('图片保存失败');
}
} catch (error) {
console.error('保存图片出错:', error);
}
}
在HarmonyOS鸿蒙Next中,使用showAssetsCreationDialog获取权限URI并保存网络图片,可以按照以下步骤进行:
- 获取权限URI:通过
requestPermissionsFromUser获取存储权限,使用showAssetsCreationDialog获取文件的URI。 - 下载图片:使用
HttpURLConnection或Fetch API下载网络图片数据。 - 保存图片:通过
FileOutputStream将图片数据写入获取的URI对应的文件中。
示例代码如下:
Uri uri = showAssetsCreationDialog();
HttpURLConnection conn = (HttpURLConnection) new URL(imageUrl).openConnection();
InputStream inputStream = conn.getInputStream();
OutputStream outputStream = getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
确保在manifest.json中声明存储权限。

