HarmonyOS 鸿蒙Next 图片文件下载保存方法:图片存图库,文件选路径后保存

发布于 1周前 作者 itying888 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 图片文件下载保存方法:图片存图库,文件选路径后保存

import type { common } from ‘@kit.AbilityKit’;
import photoAccessHelper from ‘@ohos.file.photoAccessHelper’;
import fs, { Filter, ListFileOptions } from ‘@ohos.file.fs’;
import { BusinessError } from ‘@ohos.base’;
import request from ‘@ohos.request’;
import { abilityAccessCtrl, Permissions } from ‘@kit.AbilityKit’;
import buffer from ‘@ohos.buffer’;
import dataSharePredicates from ‘@ohos.data.dataSharePredicates’;
import Url from ‘@ohos.url’
import picker from ‘@ohos.file.picker’;

@Entry
@Component
struct Index {
async getFileSaveAuthorize(): Promise<boolean> {
let hasPermissions = true
const permissions: Permissions[] =
[‘ohos.permission.READ_IMAGEVIDEO’, ‘ohos.permission.WRITE_IMAGEVIDEO’]

const permissionRes =
await abilityAccessCtrl.createAtManager()
.requestPermissionsFromUser(getContext(this) as Context, permissions)
for (const permission of permissions) {
if (!permissionRes.permissions.some(
(per, index) => per === permission && permissionRes.authResults[index] === 0
)) {
console.info(‘请授予相关权限’, permission)
hasPermissions = false
throw new Error(‘请授予相关权限’)
}
}
return hasPermissions
}

async downloadFunc(url: string) {
const authorize = await this.getFileSaveAuthorize()
if (!authorize) {
return
}

// 创建URL对象
const lastIndexOf: number = url.lastIndexOf(’.’)
// 获取路径部分(去除参数)
const path: string = url.slice(lastIndexOf,);

// 获取路径的最后一个点之后的内容作为文件扩展名
const extension: string = path.toLowerCase();


let timer: number = new Date().getTime()
let name: string = ${timer}${extension}
let that = Url.URL.parseURL(url);
let fileName: string = that.pathname.slice(that.pathname.lastIndexOf(’/’) + 1,)

let savePath = ‘’
let context = getContext(this) as common.UIAbilityContext;
console.log(‘89789’, this.checkUrlIsIMG(url));
// 这里检测下载链接是否为图片
if (this.checkUrlIsIMG(url)) {
savePath = context.cacheDir + name
} else {
savePath = context.filesDir + name
}
console.log(‘89789’, JSON.stringify(savePath));
try {
// 需要手动将 url 替换为真实服务器的 HTTP 协议地址
request.downloadFile(getContext(), { url, description: ‘即将开始下载’, filePath: savePath })
.then((data: request.DownloadTask) => {
let downloadTask: request.DownloadTask = data;
downloadTask.on(“complete”, async () => {
let file = fs.openSync(savePath, fs.OpenMode.READ_ONLY);
console.info("file fd: " + file.fd);
console.info("file fd: " + file.path);
let arrayBuffer = new ArrayBuffer(4096);
let readLen = fs.readSync(file.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);

if (this.checkUrlIsIMG(url)) {
this.saveImage(buf.buffer)
fs.closeSync(file);
} else {
this.saveFile(buf.buffer,fileName)
fs.closeSync(file);
}
})
})
.catch((err: BusinessError) => {
console.error(Failed to request the download. Code: ${err.code}, message: ${err.message});
})
} catch (err) {
console.error(Failed to request the download. err: ${JSON.stringify(err)});
}
}

async saveImage(data: ArrayBuffer | string): Promise<void> {
let context = getContext(this) as common.UIAbilityContext;
let helper = photoAccessHelper.getPhotoAccessHelper(context);
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, data);
console.log(‘写入内容’)
await fs.close(file.fd);
console.log(‘写入内容完成’)
}

async saveFile(data: ArrayBuffer | string, fileName: string): Promise<void> {
const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例
documentSaveOptions.newFileNames = [fileName]; // 保存文件名(可选)
// documentSaveOptions.fileSuffixChoices = [’.png’, ‘.txt’, ‘.mp4’]; // 保存文件类型(可选)
let uris: Array<string> = [];
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例

// documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
// uris = documentSaveResult;
// const uri = uris[0];
// let file = fs.openSync(uri, fs.OpenMode.READ_WRITE);
// // let writeLen: number = fs.writeSync(file.fd, data);
// // fs.closeSync(file);
// // console.info(‘file fd: ’ + file.fd);
// }).catch((err: BusinessError) => {
// console.error(Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message});
// })

}

//检测是否是图片
checkUrlIsIMG(url: string) {
// 创建URL对象
const lastIndexOf: number = url.lastIndexOf(’.’)
// 获取路径部分(去除参数)
const path: string = url.slice(lastIndexOf + 1,);
// 获取路径的最后一个点之后的内容作为文件扩展名
const extension: string = path.toLowerCase();
// 声明支持的图片和视频文件扩展名
const imageExtensions: Array<string> = [‘jpg’, ‘jpeg’, ‘gif’, ‘png’];
const videoExtensions: Array<string> = [‘mp4’, ‘wmv’, ‘avi’, ‘mov’];
// 判断文件扩展名是否在图片扩展名数组中
if (imageExtensions.includes(extension)) {
return ‘image’;
}
// 判断文件扩展名是否在视频扩展名数组中
if (videoExtensions.includes(extension)) {
return ‘video’;
}
// 扩展名不在图片或视频数组中,返回null表示无法确定媒体类型
return null;
}

//选择图片

async chooseImage() {
try {
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 9;
PhotoSelectOptions.isPhotoTakingSupported = true

let photoPicker = new photoAccessHelper.PhotoViewPicker();
photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ’ +
JSON.stringify(PhotoSelectResult));


}).catch((err: BusinessError) => {
console.error(PhotoViewPicker.select failed with err: ${err.code}, ${err.message});
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(PhotoViewPicker failed with err: ${err.code}, ${err.message});
}

}

build() {
Row() {
Text(‘文件下载’)

Button(‘开始下载’).onClick(() => {
this.downloadFunc(‘https://xxxxxxx.png’)
})

Button(‘开始docx下载’).onClick(() => {
this.downloadFunc(‘http://xxxxx.docx’)
})


Button(‘选择图片’).onClick(() => {
this.chooseImage()
})
}.padding({ top: 120 })
}
}
2 回复
根据代码显示let arrayBuffer = new ArrayBuffer(4096); 读取的图片过大,建议您改成 let arrayBuffer = new ArrayBuffer(fs.statSync(file.fd).size); 测试一下

在HarmonyOS(鸿蒙)系统中,实现图片文件的下载并保存到指定路径及图库,可以通过以下步骤进行编程实现:

  1. 下载图片:使用网络请求(如HTTP)下载图片数据。这通常涉及到使用HttpURLConnection或第三方网络库(如OkHttp)来发起请求并接收响应数据。

  2. 保存图片到指定路径:将下载的图片数据(通常是字节流)写入到指定路径的文件中。可以使用Java的IO流(如FileOutputStream)来完成这一操作。

  3. 将图片添加到图库:HarmonyOS提供了媒体库API,用于将新下载的图片添加到系统的媒体库中。你需要使用这些API来确保图片能够在图库中显示。这通常涉及到使用MediaStore或类似的接口来插入图片数据。

  4. 处理权限:确保应用具有读写存储空间的权限,特别是在Android 10及以上版本中,还需要处理分区存储的权限问题。

示例代码会根据具体的开发环境和需求有所不同,但上述步骤提供了一个大致的实现方向。

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

回到顶部