网络图片 / 存储到相册 / fs.copyFile
实现网络图片保存到相册推荐用什么API?
已申请ohos.permission.WRITE_IMAGEVIDEO和ohos.permission.READ_IMAGEVIDEO权限。
目前尝试的方案:第一步:下载图片到本地沙盒路径为:filePath
方案一:
let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
fs.copyFile(filePath, uri)//这一步一直报错:No such file or directory, code:13900002
方案二:
let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
let fetchOption: photoAccessHelper.FetchOptions = {
fetchColumns: [],
predicates: predicates
};
let albumFetchResult: photoAccessHelper.FetchResult = await phAccessHelper.getAlbums( photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject()
let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();album.addAssets([asset], (err) => {});
方案一的问题:可以把相册中已有的图片添加到用户新建的相册中,如果用户没有新建相册,则不成功,请问可以不指定用户新建的相册么?
代码参考:https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V2/photoaccesshelper-useralbum-guidelines-0000001608076068-V2
方案二的问题:如何用filePath构造出photoAccessHelper.PhotoAsset对象,然后调用album.addAssets?
方案一是可行的,报错的原因:fs.copyFile的dest不支持uri,可以打开后再使用。
请参考代码如下:
let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
let filePath = this.resourcesFile2SandboxFile($r('app.media.test'));
let destFile: fileIo.File = fs.openSync(uri, fileIo.OpenMode.READ_WRITE);
fs.copyFile(filePath, destFile.fd).then(() => {
console.info("copy file succeed");
}).catch((err: BusinessError) => {
console.error("copy file failed with error message: " + err.message + ", error code: " + err.code);
});