HarmonyOS 通过网络下载的文件,能否写入系统Download目录

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
superinsect

可以参考

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 '@ohos.request';


@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  build() {
    RelativeContainer() {
      Button('下载文件')
        .onClick(() => {
          this.saveFile()
        })
    }
    .height('100%')
    .width('100%')
  }
  saveFile() {
    try {
      let context = getContext(this) as common.Context;
      let documentSaveOptions = new picker.DocumentSaveOptions();
      documentSaveOptions.newFileNames = ['dog.png'];
      let documentPicker = new picker.DocumentViewPicker(context);
      documentPicker.save(documentSaveOptions).then(async (documentSaveResult: Array<string>) => {
        console.info('DocumentViewPicker.save successfully, documentSaveResult uri: ' + JSON.stringify(documentSaveResult));
        let uri = documentSaveResult[0];
        this.downloadFile(uri);
      })
    } catch (err) {
      console.log(err)
    }
  }
  downloadFile(uri: string) {
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    try {
      request.downloadFile(context, {
        url: 'https://img1.xxx.com/it/u=2367369659,1112354818&fm=253&fmt=auto&app=120&f=JPEG?w=667&h=500',
        filePath: filesDir + '/dog.png'
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          console.info('download complete');
          //需要复制的文件
          let readFile = fs.openSync(context.filesDir + '/dog.png', fs.OpenMode.READ_ONLY)
          let writeFile = fs.openSync(uri, fs.OpenMode.READ_WRITE)
          fs.copyFileSync(readFile.fd, writeFile.fd)
          fs.closeSync(readFile)
          fs.closeSync(writeFile)
        })
      }).catch((err: BusinessError) => {
        console.error(Invoke downloadTask failed, code is ${err.code}, message is ${err.message});
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(Invoke downloadFile failed, code is ${err.code}, message is ${err.message});
    }
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 下载报错Download File Path Valid
877浏览 • 1回复 待解决
HarmonyOS 下载文件并保存到指定目录
96浏览 • 1回复 待解决