如何保存一张远程图片到本地文件的公共目录的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://图片资源路径`,
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}, 1message 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() {
}
}
目前不支持download模式直接去调fs保存文件,这样拿到的uri是没有操作权限的;需要下载文件到公共路径还是推荐下载后picker保存到指定路径的方式