HarmonyOS 网络文件下载到公共目录示例?

如题:HarmonyOS 网络文件下载到公共目录示例?

阅读 425
1 个回答

示例参考:

// 将网络资源文件下载到应用文件目录并读取一段内容
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
import buffer from '@ohos.buffer';
import { picker } from '@kit.CoreFileKit';

@Entry
@Component
struct Index {
  build() {
    Button().onClick(() => {
      let context = getContext(this) as common.UIAbilityContext;
      let filePath = context.filesDir + "/test.xlsx";
      let url = "http://huawei.com"
      try {
        request.downloadFile(context, {
          url: url,
          filePath: filePath
        }).then((data: request.DownloadTask) => {
          let downloadTask: request.DownloadTask = data;
          downloadTask.on('complete', () => {
            console.info('download complete');
            let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            let arrayBuffer = new ArrayBuffer(4096000);
            let readLen = fs.readSync(file.fd, arrayBuffer);
            let buf = buffer.from(arrayBuffer, 0, readLen);
            console.info(`content of File: ${buf.toString()}`);
            let writeLen = fs.writeSync(file.fd, arrayBuffer);
            fs.closeSync(file);

            const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例
            // documentSaveOptions.newFileNames = ["1.xlsx"]; // 保存文件名(可选)
            // documentSaveOptions.fileSuffixChoices = ['xlsx']; // 保存文件类型(可选)
            let uris: Array<string> = [];
            const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
            documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array<string>) => {
              uris = documentSaveResult;
              console.info('documentViewPicker.save to file succeed and uris are:' + uris);
              let uri = uris[0];
              let file2 = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
              let writeLen2 = fs.writeSync(file2.fd, arrayBuffer);
              fs.closeSync(file2);
            }).catch((err: BusinessError) => {
              console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
            })
          })

          let failCallback = () => {
            console.info('Download task fail.');
          };
          downloadTask.on('fail', failCallback);
        }).catch((err: BusinessError) => {
          console.error(`downLoadFileTask failed, code is ${err.code}, message is ${err.message}`);
        });
      } catch (error) {
        console.error(`downLoadFileTask failed, code is ${error.code}, message is ${error.message}`);
      }
    })
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏