目录

How do I set the saveas parameter in request.agent.Config?

Question

How do I set the download save path to getHostContext().filesDir by setting the saveas parameter?

Answer

For details about the saveas parameter, see request.agent.Config. The saveas parameter supports the following paths:

  1. Relative path, which is in the cache directory of the caller, for example, ./xxx/yyy/zzz.html or xxx/yyy/zzz.html.
  2. Internal protocol path. Only internal://cache/ and its subpaths are supported, for example, internal://cache/path/to/file.txt.
  3. Application sandbox directory. Only the base directory and its subdirectories are supported, for example, /data/storage/el1/base/path/to/file.txt.
  4. File protocol path, which must match the application bundle name. Only the base directory and its subdirectories are supported, for example, file://com.example.test/data/storage/el2/base/file.txt.

The relative path is used by default.

You can set the saveas parameter to set the download save path to getHostContext().filesDir.

Reference code

Add the network access permission ohos.permission.INTERNET to the module.json5 configuration file in the project.

import { webview } from '@kit.ArkWeb';
import { request } from '@kit.BasicServicesKit';

// In the utility class, retrieve the Context from the Entry Ability and save it to AppStore, then use AppStore to retrieve it in the utility class
let context = AppStorage.get("context") as UIContext;
let filesDir = context.getHostContext()!.filesDir;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'https://www-file.huawei.com/minisite/media/annual_report/annual_report_2023_cn.pdf',
  title: 'createTest',
  description: 'Sample code for create task',
  mode: request.agent.Mode.FOREGROUND,
  overwrite: true,
  method: "get",
  saveas: filesDir + '/test.pdf',
  network: request.agent.Network.WIFI,
  metered: false,
  roaming: true,
  retry: true,
  redirect: true,
  index: 0,
  begins: 0,
  ends: -1,
  gauge: false,
  precise: false,
  token: 'it is a secret'
};
let createOnCallback = (progress: request.agent.Progress) => {
  console.info('upload task progress.');
};

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  @State uri: string = '';
  @State isChange: boolean = false;

  build() {
    Column() {
      Button('Refresh UI')
        .width('200vp')
        .onClick(() => {
          this.controller.loadUrl('file://' + filesDir + '/test.pdf')
        })
        .margin({ bottom: '20vp' })
      Web({ src: $rawfile('test.html'), controller: this.controller })
        .domStorageAccess(true)
        .onPageBegin((event)=>{
          request.agent.create(this.getUIContext().getHostContext(), config).then((task: request.agent.Task) => {
            task.on('progress', createOnCallback);
            console.info(`Succeeded in creating a download task. result: ${task.config}`);
            task.start();
          }).catch((err: Error) => {
            console.error(`Failed to create a download task, message: ${err.message}`);
          });
        })
    }
  }
}