HarmonyOS 鸿蒙Next如何保存一张远程图片到本地文件的公共目录的DOWNLOAD文件夹
HarmonyOS 鸿蒙Next如何保存一张远程图片到本地文件的公共目录的DOWNLOAD文件夹 如何保存一张远程图片到本地文件的公共目录的DOWNLOAD文件夹,保存一张http图片到本地的公共目录的DOWNLOAD文件夹,参考了
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/save-user-file-V5#保存文档类文件
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/save-user-file-V5#download模式保存文件
均未成功实现。希望您能帮我改一下。
我的最小化 demo如下:
import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
import common from '@ohos.app.ability.common';
import { request } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
aboutToAppear(): void {
let uri: string = '';
let context = getContext(this) as common.Context;
const tempDir = context.tempDir;
const documentViewPicker = new picker.DocumentViewPicker(context);
const documentSaveOptions = new picker.DocumentSaveOptions();
documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD;
documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
uri = documentSaveResult[0];
let tmpfile = `${tempDir}/${Date.now()}.png`
request.downloadFile(context, {
url: `https://xxx.png`,
filePath: tmpfile
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
console.info('download complete');
let file = fs.openSync(tmpfile, fs.OpenMode.READ_WRITE);
let buf = new ArrayBuffer(fs.statSync(file.fd).size);
fs.readSync(file.fd, buf);
fs.copyFileSync(tmpfile, `${uri}/${Date.now()}.png`, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
fs.closeSync(file);
})
}).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
});
console.info('documentViewPicker.save succeed and uri is:' + uri);
}).catch((err: BusinessError) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
}
build() {
}
}
更多关于HarmonyOS 鸿蒙Next如何保存一张远程图片到本地文件的公共目录的DOWNLOAD文件夹的实战教程也可以访问 https://www.itying.com/category-93-b0.html
更多关于HarmonyOS 鸿蒙Next如何保存一张远程图片到本地文件的公共目录的DOWNLOAD文件夹的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙)系统中,保存一张远程图片到本地文件的公共目录DOWNLOAD文件夹,可以通过以下步骤实现:
-
获取远程图片数据:
- 使用网络请求库(如
OkHttp
,但注意鸿蒙有自己的网络请求API,如HttpURLConnection
或HttpClient
)获取远程图片的二进制数据。
- 使用网络请求库(如
-
获取DOWNLOAD目录路径:
- 使用鸿蒙的文件管理API获取公共目录DOWNLOAD的路径。可以通过
FileProvider
或者鸿蒙的文件访问权限API来获取该路径。
- 使用鸿蒙的文件管理API获取公共目录DOWNLOAD的路径。可以通过
-
保存图片到指定路径:
- 将获取到的图片二进制数据写入到上一步获取的DOWNLOAD目录路径下的文件中。注意文件名的唯一性,避免覆盖已有文件。
-
处理权限问题:
- 确保应用在manifest文件中声明了必要的文件读写权限,并在运行时请求用户授权。
示例代码(伪代码,具体实现需根据鸿蒙API调整):
// 伪代码,具体API需查阅鸿蒙开发文档
String imageUrl = "远程图片URL";
byte[] imageData = fetchImageDataFromUrl(imageUrl); // 自定义方法获取图片数据
String downloadDir = getDownloadDirPath(); // 自定义方法获取DOWNLOAD目录路径
File file = new File(downloadDir, "imageName.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(imageData);
fos.close();
如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html,