HarmonyOS鸿蒙Next下载咨询
HarmonyOS鸿蒙Next下载咨询
您好,我要下载网络上的图片或文件,因为没有权限,我要怎么下载到相册? 下面就是我现在写的下载函数,但无法下载,提示没有权限,我要怎么下载? 同时问一下,下载下来的文件,我怎么给它自定义名称?
function httpDownGet(url: string, context: Context, i_fs: number): Promise<string> { let httpRequest = http.createHttp(); let responseResult = httpRequest.request(url, { method: http.RequestMethod.GET, connectTimeout: 60000, readTimeout: 60000 });
// Processes the data and returns.
return responseResult.then(async (value: http.HttpResponse) => {
//console.error("------------responseResult数据----: " + JSON.stringify(value));
if (value.responseCode === Const.HTTP_CODE_200) {
let imageBuffer: ArrayBuffer = value.result as ArrayBuffer;
try {
// 获取相册路径
let helper = photoAccessHelper.getPhotoAccessHelper(context);
let tmp_fix = 'jpg';
if (i_fs === 2) {
tmp_fix = 'png';
} else if (i_fs === 3) {
tmp_fix = 'gif';
}
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, tmp_fix);
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
// 写入文件
await fileIo.write(file.fd, imageBuffer);
// 关闭文件
await fileIo.close(file.fd);
return 'ok';
} catch (error) {
console.error("-----------error is " + JSON.stringify(error));
return '';
}
} else {
return '';
}
}).catch((e: string) => {
console.error("-------------error-----", e);
return '';
})
}
更多关于HarmonyOS鸿蒙Next下载咨询的实战教程也可以访问 https://www.itying.com/category-93-b0.html
网络图片下载保存到相册需要配置以下两种权限
ohos.permission.INTERNET
ohos.permission.WRITE_IMAGEVIDEO
其中ohos.permission.WRITE_IMAGEVIDEO需要向用户申请授权,可参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/request-user-authorization-V5
提供个下载图片至相册的demo,您借鉴一下
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import ResponseCode from '[@ohos](/user/ohos).net.http';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '[@ohos](/user/ohos).file.fs';
@Entry
@Component
struct Index {
loadImageWithUrl(url: string) {
// 使用 request 下载图片并在回调函数中保存图片到相册
http.createHttp().request(url, {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000
}, async (error: BusinessError, data: http.HttpResponse) => {
if (error) {
console.error(`HTTP request failed with code: ${error.code}, message: ${error.message}`);
} else {
if (ResponseCode.ResponseCode.OK === data.responseCode) {
let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
try {
// 获取相册路径
const context = this.getContext();
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, imageBuffer);
// 关闭文件
await fs.close(file.fd);
} catch (error) {
console.error("Error is: " + JSON.stringify(error));
}
} else {
console.error("Error occurred when image downloaded!");
}
}
});
}
}
上传文件或者图片的时候文件名是已经定义好的,不可以自定义,可在API文档里搜一下fileName
除此之外上传下载也可使用@ohos.request接口:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5
ohos.permission.WRITE_IMAGEVIDEO权限是必须的,其配置、申请如下:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-image-9-V5
还可以看一下这个临时授权:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-image-13-V5
更多关于HarmonyOS鸿蒙Next下载咨询的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
下载网络图片到相册的页面
这是我们的下载网络图片到相册的页面,用的系统的安全控件(这个可以不用权限),不用安全控件的保存图片到相册需要申请系统权限,比较麻烦点。
@Component
export struct ImageSavePage {
url?: string
build() {
NavDestination() {
TitleBarView({ title: "" })
Image(this.url)
.objectFit(ImageFit.Auto)
.layoutWeight(1)
.width('100%')
Stack({ alignContent: Alignment.Center }) {
SaveButton({ text: SaveDescription.SAVE_IMAGE })
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result === SaveButtonOnClickResult.SUCCESS) {
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
this.saveImage(context, `${this.url}`);
} else {
promptAction.showToast({ message: '设置权限失败!' })
}
})
}
.height(140)
.width('100%')
}.hideTitleBar(true)
}
async saveImage(context: common.UIAbilityContext, url: string): Promise<void> {
axios.get(url, { responseType: 'array_buffer' }).then(async (res: AxiosResponse<ArrayBuffer>) => {
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, res.data);
await fs.close(file.fd);
promptAction.showToast({ message: '已保存至相册!' });
})
}
}
@Builder
export function harBuilder(value: object) {
ImageSavePage({ url: (value as String).toString() })
}
const builderName = BuilderNameConstants.IMAGE_SAVE_PAGE;
if (!RouterModule.getBuilder(builderName)) {
const builder: WrappedBuilder<[object]> = wrapBuilder(harBuilder);
RouterModule.registerBuilder(builderName, builder);
}
HarmonyOS Next是华为推出的新一代操作系统,支持多设备协同,提升用户体验。您可以通过华为开发者联盟官网或华为应用市场下载。建议使用华为设备以确保最佳兼容性。下载前请确认设备型号和系统版本,并确保网络稳定。


