harmony 鸿蒙@ohos.request (上传下载)

  • 2022-08-09
  • 浏览 (592)

@ohos.request (上传下载)

request部件主要给应用提供上传下载文件、后台传输代理的基础能力。

说明:

本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import request from '@ohos.request';

常量

需要权限:ohos.permission.INTERNET

系统能力: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。

网络类型

下载支持自定义网络类型,可以在DownloadConfig中通过networkType配置成以下网络类型。

名称 参数类型 数值 说明
NETWORK_MOBILE number 0x00000001 使用蜂窝网络时允许下载的位标志。
NETWORK_WIFI number 0x00010000 使用WLAN时允许下载的位标志。

下载任务的错误码

下载on(‘fail’)7+事件callback的错误参数、getTaskInfo9+返回值的failedReason字段取值。

名称 参数类型 数值 说明
ERROR_CANNOT_RESUME7+ number 0 网络原因导致恢复下载失败。
ERROR_DEVICE_NOT_FOUND7+ number 1 找不到SD卡等存储设备。
ERROR_FILE_ALREADY_EXISTS7+ number 2 要下载的文件已存在,下载会话不能覆盖现有文件。
ERROR_FILE_ERROR7+ number 3 文件操作失败。
ERROR_HTTP_DATA_ERROR7+ number 4 HTTP传输失败。
ERROR_INSUFFICIENT_SPACE7+ number 5 存储空间不足。
ERROR_TOO_MANY_REDIRECTS7+ number 6 网络重定向过多导致的错误。
ERROR_UNHANDLED_HTTP_CODE7+ number 7 无法识别的HTTP代码。
ERROR_UNKNOWN7+ number 8 未知错误。
ERROR_OFFLINE9+ number 9 网络未连接。
ERROR_UNSUPPORTED_NETWORK_TYPE9+ number 10 网络类型不匹配。

下载任务暂停原因

下载相关getTaskInfo9+返回值的pausedReason字段取值。

名称 参数类型 数值 说明
PAUSED_QUEUED_FOR_WIFI7+ number 0 下载被暂停并等待WLAN连接,因为文件大小超过了使用蜂窝网络的会话允许的最大值。
PAUSED_WAITING_FOR_NETWORK7+ number 1 由于网络问题(例如网络断开)而暂停下载。
PAUSED_WAITING_TO_RETRY7+ number 2 发生网络错误,将重试下载会话。
PAUSED_BY_USER9+ number 3 用户暂停会话。
PAUSED_UNKNOWN7+ number 4 未知原因导致暂停下载。

下载任务状态码

下载相关getTaskInfo9+返回值的status字段取值。

名称 参数类型 数值 说明
SESSION_SUCCESSFUL7+ number 0 下载会话已完成。
SESSION_RUNNING7+ number 1 下载会话正在进行中。
SESSION_PENDING7+ number 2 正在调度下载会话。
SESSION_PAUSED7+ number 3 下载会话已暂停。
SESSION_FAILED7+ number 4 下载会话已失败,将不会重试。

request.uploadFile9+

uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask>

上传,异步方法,使用promise形式返回结果。通过on(‘complete’|‘fail’)9+可获取任务上传时的错误信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
context BaseContext 基于应用程序的上下文。
config UploadConfig 上传的配置信息。

返回值:

类型 说明
Promise<UploadTask> 返回上传任务。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400002 bad file path.

示例:

  let uploadTask: request.UploadTask;
  let uploadConfig: request.UploadConfig = {
    url: 'http://www.example.com', //需要手动替换为真实服务器地址
    header: { 'Accept': '*/*' },
    method: "POST",
    files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
    data: [{ name: "name123", value: "123" }],
  };
  try {
    request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
      uploadTask = data;
    }).catch((err: BusinessError) => {
      console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
    });
  } catch (err) {
    console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
  }

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.uploadFile9+

uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void

上传,异步方法,使用callback形式返回结果。通过on(‘complete’|‘fail’)9+可获取任务上传时的错误信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
context BaseContext 基于应用程序的上下文。
config UploadConfig 上传的配置信息。
callback AsyncCallback<UploadTask> 回调函数,异步返回UploadTask对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400002 bad file path.

示例:

  let uploadTask: request.UploadTask;
  let uploadConfig: request.UploadConfig = {
    url: 'http://www.example.com', //需要手动替换为真实服务器地址
    header: { 'Accept': '*/*' },
    method: "POST",
    files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
    data: [{ name: "name123", value: "123" }],
  };
  try {
    request.uploadFile(getContext(), uploadConfig, (err: BusinessError, data: request.UploadTask) => {
      if (err) {
        console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
        return;
      }
      uploadTask = data;
    });
  } catch (err) {
    console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
  }

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.upload(deprecated)

upload(config: UploadConfig): Promise<UploadTask>

上传,异步方法,使用promise形式返回结果。

模型约束:此接口仅可在FA模型下使用

说明: 从API Version 9开始不再维护,建议使用request.uploadFile9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
config UploadConfig 上传的配置信息。

返回值:

类型 说明
Promise<UploadTask> 返回上传任务。

示例:

  let uploadTask;
  let uploadConfig = {
    url: 'http://www.example.com', //需要手动替换为真实服务器地址
    header: { 'Accept': '*/*' },
    method: "POST",
    files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
    data: [{ name: "name123", value: "123" }],
  };
  request.upload(uploadConfig).then((data) => {
    uploadTask = data;
  }).catch((err) => {
    console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
  })

request.upload(deprecated)

upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void

上传,异步方法,使用callback形式返回结果。

模型约束:此接口仅可在FA模型下使用

说明: 从API Version 9开始不再维护,建议使用request.uploadFile9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
config UploadConfig 上传的配置信息。
callback AsyncCallback<UploadTask> 回调函数,异步返回UploadTask对象。

示例:

  let uploadTask;
  let uploadConfig = {
    url: 'http://www.example.com', //需要手动替换为真实服务器地址
    header: { 'Accept': '*/*' },
    method: "POST",
    files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
    data: [{ name: "name123", value: "123" }],
  };
  request.upload(uploadConfig, (err, data) => {
    if (err) {
      console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    uploadTask = data;
  });

UploadTask

上传任务,使用下列方法前,需要先获取UploadTask对象,promise形式通过request.uploadFile9+获取,callback形式通过request.uploadFile9+获取。

on(‘progress’)

on(type: ‘progress’, callback:(uploadedSize: number, totalSize: number) => void): void

订阅上传任务进度监听,同步方法,使用callback形式返回结果。

说明:

当应用处于后台时,为满足功耗性能要求,不支持调用此接口进行回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’progress’(上传的进度信息)。
callback function 上传进度的回调函数。

回调函数的参数

参数名 类型 必填 说明
uploadedSize number 当前已上传文件大小,单位为B。
totalSize number 上传文件的总大小,单位为B。

示例:

  let upProgressCallback = (uploadedSize: number, totalSize: number) => {
    console.info("upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize);
  };
  uploadTask.on('progress', upProgressCallback);

on(‘headerReceive’)7+

on(type: ‘headerReceive’, callback: (header: object) => void): void

订阅上传任务HTTP标头监听,同步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’headerReceive’(接收响应头)。
callback function HTTP Response Header事件的回调函数。

回调函数的参数:

参数名 类型 必填 说明
header object HTTP Response Header。

示例:

  let headerCallback = (headers: object) => {
    console.info("upOnHeader headers:" + JSON.stringify(headers));
  };
  uploadTask.on('headerReceive', headerCallback);

on(‘complete’|‘fail’)9+

on(type:‘complete’|‘fail’, callback: Callback<Array<TaskState>>): void;

订阅上传任务完成或失败监听,同步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’complete’,表示上传任务完成;取值为’fail’,表示上传任务失败。
callback Callback<Array<TaskState>> 上传任务完成或失败的回调函数。

回调函数的参数

参数名 类型 必填 说明
taskstates Array<TaskState> 上传任务返回结果

示例:

  let upCompleteCallback = (taskStates: Array<request.TaskState>) => {
    for (let i = 0; i < taskStates.length; i++) {
      console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
    }
  };
  uploadTask.on('complete', upCompleteCallback);

  let upFailCallback = (taskStates: Array<request.TaskState>) => {
    for (let i = 0; i < taskStates.length; i++) {
      console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
    }
  };
  uploadTask.on('fail', upFailCallback);

off(‘progress’)

off(type: ‘progress’, callback?: (uploadedSize: number, totalSize: number) =&gt; void): void

取消订阅上传任务进度监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 取消订阅的事件类型,取值为’progress’(上传的进度信息)。
callback function 需要删除的上传任务进度的回调函数。
uploadedSize:当前已上传文件的大小,单位为B。
totalSize:上传文件的总大小,单位为B。

示例:

  let upProgressCallback = (uploadedSize: number, totalSize: number) => {
    console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize);
  };
  uploadTask.off('progress', upProgressCallback);

off(‘headerReceive’)7+

off(type: ‘headerReceive’, callback?: (header: object) =&gt; void): void

取消订阅上传任务HTTP标头监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 取消订阅的事件类型,取值为’headerReceive’(接收响应头)。
callback function HTTP&nbsp;Response&nbsp;需要删除的Header事件的回调函数。
header:HTTP&nbsp;Response&nbsp;Header。

示例:

  let headerCallback = (header: object) => {
    console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`);
  };
  uploadTask.off('headerReceive', headerCallback);

off(‘complete’|‘fail’)9+

off(type:‘complete’|‘fail’, callback?: Callback&lt;Array&lt;TaskState&gt;&gt;): void;

取消订阅上传任务完成或失败监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’complete’,表示上传任务完成;取值为’fail’,表示上传任务失败。
callback Callback&lt;Array&lt;TaskState&gt;&gt; 需要删除的上传任务完成或失败的回调函数。
taskstates:上传任务返回结果

示例:

  let upCompleteCallback = (taskStates: Array<request.TaskState>) => {
    console.info('Upload delete complete notification.');
    for (let i = 0; i < taskStates.length; i++) {
      console.info('taskState:' + JSON.stringify(taskStates[i]));
    }
  };
  uploadTask.off('complete', upCompleteCallback);

  let upFailCallback = (taskStates: Array<request.TaskState>) => {
    console.info('Upload delete fail notification.');
    for (let i = 0; i < taskStates.length; i++) {
      console.info('taskState:' + JSON.stringify(taskStates[i]));
    }
  };
  uploadTask.off('fail', upFailCallback);

delete9+

delete(): Promise&lt;boolean&gt;

移除上传的任务,异步方法,使用promise形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

返回值:

类型 说明
Promise&lt;boolean&gt; 移除任务是否成功。true:成功,false:不成功。

示例:

  uploadTask.delete().then((result: boolean) => {
    console.info('Succeeded in deleting the upload task.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
  });

delete9+

delete(callback: AsyncCallback&lt;boolean&gt;): void

移除上传的任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 移除任务的回调函数。

示例:

  uploadTask.delete((err: BusinessError, result: boolean) => {
    if (err) {
      console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in deleting the upload task.');
  });

remove(deprecated)

remove(): Promise&lt;boolean&gt;

移除上传的任务,异步方法,使用promise形式返回结果。

说明: 从API Version 9开始不再维护,建议使用delete9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

返回值:

类型 说明
Promise&lt;boolean&gt; 移除任务是否成功。true:成功,false:不成功。

示例:

  uploadTask.remove().then((result) => {
    console.info('Succeeded in removing the upload task.');
  }).catch((err) => {
    console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
  });

remove(deprecated)

remove(callback: AsyncCallback&lt;boolean&gt;): void

移除上传的任务,异步方法,使用callback形式返回结果。

说明: 从API Version 9开始不再维护,建议使用delete9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 移除任务的回调函数。

示例:

  uploadTask.remove((err, result) => {
    if (err) {
      console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    if (result) {
      console.info('Succeeded in removing the upload task.');
    } else {
      console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`);
    }
  });

UploadConfig

上传任务的配置信息。

需要权限:ohos.permission.INTERNET

系统能力: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。

名称 类型 必填 说明
url string 资源地址。
header Object 添加要包含在上传请求中的HTTP或HTTPS标志头。
method string 请求方法:POST、PUT。缺省为POST。
index number 任务的路径索引,默认值为0。
begins number 在上传开始时读取的文件起点。默认值为0,取值为闭区间。
ends number 在上传结束时读取的文件终点。默认值为-1,取值为闭区间。
files Array&lt;File&gt; 要上传的文件列表。请使用&nbsp;multipart/form-data提交。
data Array&lt;RequestData&gt; 请求的表单数据。

TaskState9+

上传任务信息,on(‘complete’|‘fail’)9+off(‘complete’|‘fail’)9+接口的回调参数。

需要权限:ohos.permission.INTERNET

系统能力: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。

名称 类型 必填 说明
path string 文件路径
responseCode number 上传任务返回值,0表示任务成功,其它返回码为失败,具体请查看message上传任务结果描述信息
message string 上传任务结果描述信息

File

UploadConfig中的文件列表。

需要权限:ohos.permission.INTERNET

系统能力: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。

名称 类型 必填 说明
filename string multipart提交时,请求头中的文件名。
name string multipart提交时,表单项目的名称,缺省为file。
uri string 文件的本地存储路径。
仅支持”internal”协议类型,”internal://cache/“为必填字段,示例:
internal://cache/path/to/file.txt
type string 文件的内容类型,默认根据文件名或路径的后缀获取。

RequestData

UploadConfig中的表单数据。

需要权限:ohos.permission.INTERNET

系统能力: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。

名称 类型 必填 说明
name string 表示表单元素的名称。
value string 表示表单元素的值。

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;

下载,异步方法,使用promise形式返回结果。通过on(‘complete’|‘pause’|‘remove’)7+可获取任务下载时的状态信息,包括任务完成、暂停或移除。通过on(‘fail’)7+可获取任务下载时的错误信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
context BaseContext 基于应用程序的上下文。
config DownloadConfig 下载的配置信息。

返回值:

类型 说明
Promise&lt;DownloadTask&gt; 返回下载任务。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400001 file operation error.
13400002 bad file path.
13400003 task service ability error.

示例:

  let downloadTask: request.DownloadTask;
  try {
    request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
      downloadTask = data;
    }).catch((err: BusinessError) => {
      console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
    })
  } catch (err) {
    console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
  }

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;

下载,异步方法,使用callback形式返回结果。通过on(‘complete’|‘pause’|‘remove’)7+可获取任务下载时的状态信息,包括任务完成、暂停或移除。通过on(‘fail’)7+可获取任务下载时的错误信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
context BaseContext 基于应用程序的上下文。
config DownloadConfig 下载的配置信息。
callback AsyncCallback&lt;DownloadTask&gt; 下载接口的回调函数。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400001 file operation error.
13400002 bad file path.
13400003 task service ability error.

示例:

  let downloadTask: request.DownloadTask;
  try {
    request.downloadFile(getContext(), {
      url: 'https://xxxx/xxxxx.hap',
      filePath: 'xxx/xxxxx.hap'
    }, (err: BusinessError, data: request.DownloadTask) => {
      if (err) {
        console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
        return;
      }
      downloadTask = data;
    });
  } catch (err) {
    console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
  }

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.download(deprecated)

download(config: DownloadConfig): Promise&lt;DownloadTask&gt;

下载,异步方法,使用promise形式返回结果。

说明: 从API Version 9开始不再维护,建议使用request.downloadFile9+替代。

模型约束:此接口仅可在FA模型下使用

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
config DownloadConfig 下载的配置信息。

返回值:

类型 说明
Promise&lt;DownloadTask&gt; 返回下载任务。

示例:

  let downloadTask;
  request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => {
    downloadTask = data;
  }).catch((err) => {
    console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
  })

request.download(deprecated)

download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void

下载,异步方法,使用callback形式返回结果。

说明: 从API Version 9开始不再维护,建议使用request.downloadFile9+替代。

模型约束:此接口仅可在FA模型下使用

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
config DownloadConfig 下载的配置信息。
callback AsyncCallback&lt;DownloadTask&gt; 下载接口的回调函数。

示例:

  let downloadTask;
  request.download({ url: 'https://xxxx/xxxxx.hap', 
  filePath: 'xxx/xxxxx.hap'}, (err, data) => {
    if (err) {
      console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    downloadTask = data;
  });

DownloadTask

下载任务,使用下列方法前,需要先获取DownloadTask对象,promise形式通过request.downloadFile9+获取,callback形式通过request.downloadFile9+获取。

on(‘progress’)

on(type: ‘progress’, callback:(receivedSize: number, totalSize: number) =&gt; void): void

订阅下载任务进度监听,同步方法,使用callback形式返回结果。

说明:

当应用处于后台时,为满足功耗性能要求,不支持调用此接口进行回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’progress’(下载的进度信息)。
callback function 下载任务进度的回调函数。

回调函数的参数:

参数名 类型 必填 说明
receivedSize number 当前下载的进度,单位为B。
totalSize number 下载文件的总大小,单位为B。

示例:

  let progressCallback = (receivedSize: number, totalSize: number) => {
    console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
  };
  downloadTask.on('progress', progressCallback);

off(‘progress’)

off(type: ‘progress’, callback?: (receivedSize: number, totalSize: number) =&gt; void): void

取消订阅下载任务进度监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 取消订阅的事件类型,取值为’progress’(下载的进度信息)。
callback function 需要删除的下载任务进度的回调。
receivedSize:当前下载任务的进度;
totalSize:下载文件的总大小。

示例:

  let progressCallback = (receivedSize: number, totalSize: number) => {
    console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize);
  };
  downloadTask.off('progress', progressCallback);

on(‘complete’|‘pause’|‘remove’)7+

on(type: ‘complete’|‘pause’|‘remove’, callback:() =&gt; void): void

订阅下载任务相关的监听,异步方法,使用callback形式返回。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 订阅的事件类型。
- 取值为’complete’,表示下载任务完成;
- 取值为’pause’,表示下载任务暂停;
- 取值为’remove’,表示下载任务移除。
callback function 下载任务相关的回调函数。

示例:

  let completeCallback = () => {
    console.info('Download task completed.');
  };
  downloadTask.on('complete', completeCallback);

  let pauseCallback = () => {
    console.info('Download task pause.');
  };
  downloadTask.on('pause', pauseCallback);

  let removeCallback = () => {
    console.info('Download task remove.');
  };
  downloadTask.on('remove', removeCallback);

off(‘complete’|‘pause’|‘remove’)7+

off(type: ‘complete’|‘pause’|‘remove’, callback?:() =&gt; void): void

取消订阅下载任务相关的监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 取消订阅的事件类型。
- 取值为’complete’,表示下载任务完成;
- 取值为’pause’,表示下载任务暂停;
- 取值为’remove’,表示下载任务移除。
callback function 需要删除的下载任务相关的回调。

示例:

  let completeCallback = () => {
    console.info('Download delete complete notification.');
  };
  downloadTask.off('complete', completeCallback);

  let pauseCallback = () => {
    console.info('Download delete pause notification.');
  };
  downloadTask.off('pause', pauseCallback);

  let removeCallback = () => {
    console.info('Download delete remove notification.');
  };
  downloadTask.off('remove', removeCallback);

on(‘fail’)7+

on(type: ‘fail’, callback: (err: number) =&gt; void): void

订阅下载任务失败监听,同步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 订阅的事件类型,取值为’fail’(下载失败)。
callback function 下载失败的回调函数。

回调函数的参数:

参数名 类型 必填 说明
err number 下载失败的错误码,错误原因见下载任务的错误码

示例:

  let failCallback = (err: number) => {
    console.error(`Failed to download the task. Code: ${err}`);
  };
  downloadTask.on('fail', failCallback);

off(‘fail’)7+

off(type: ‘fail’, callback?: (err: number) =&gt; void): void

取消订阅下载任务失败监听,同步方法。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
type string 取消订阅的事件类型,取值为’fail’(下载失败)。
callback function 需要删除的下载失败的回调函数。
err:下载失败的错误码。

示例:

  let failCallback = (err: number) => {
    console.error(`Failed to download the task. Code: ${err}`);
  };
  downloadTask.off('fail', failCallback);

delete9+

delete(): Promise&lt;boolean&gt;

移除下载的任务,异步方法,使用promise形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;boolean&gt; 移除任务是否成功。

示例:

  downloadTask.delete().then((result: boolean) => {
    console.info('Succeeded in removing the download task.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
  });

delete9+

delete(callback: AsyncCallback&lt;boolean&gt;): void

移除下载的任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 移除任务是否成功。

示例:

  downloadTask.delete((err: BusinessError, result: boolean) => {
    if (err) {
      console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in removing the download task.');
  });

getTaskInfo9+

getTaskInfo(): Promise&lt;DownloadInfo&gt;

查询下载任务,异步方法,使用promise形式返回DownloadInfo里的信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;DownloadInfo&gt; 查询下载任务信息。

示例:

  downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => {
    console.info('Succeeded in querying the download task')
  }).catch((err: BusinessError) => {
    console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
  });

getTaskInfo9+

getTaskInfo(callback: AsyncCallback&lt;DownloadInfo&gt;): void

查询下载的任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;DownloadInfo&gt; 查询下载任务的回调函数。

示例:

  downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => {
    if (err) {
      console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
    } else {
      console.info('Succeeded in querying the download mimeType');
    }
  });

getTaskMimeType9+

getTaskMimeType(): Promise&lt;string&gt;

查询下载的任务的 MimeType,异步方法,使用promise形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;string&gt; 查询下载任务的MimeType。

示例:

  downloadTask.getTaskMimeType().then((data: string) => {
    console.info('Succeeded in querying the download MimeType');
  }).catch((err: BusinessError) => {
    console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
  });

getTaskMimeType9+

getTaskMimeType(callback: AsyncCallback&lt;string&gt;): void;

查询下载的任务的 MimeType,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;string&gt; 查询下载任务的MimeType的回调函数。

示例:

  downloadTask.getTaskMimeType((err: BusinessError, data: string) => {
    if (err) {
      console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
    } else {
      console.info('Succeeded in querying the download mimeType');
    }
  });

suspend9+

suspend(): Promise&lt;boolean&gt;

暂停下载任务,异步方法,使用promise形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;boolean&gt; 暂停下载任务是否成功。

示例:

  downloadTask.suspend().then((result: boolean) => {
    console.info('Succeeded in pausing the download task.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
  });

suspend9+

suspend(callback: AsyncCallback&lt;boolean&gt;): void

暂停下载任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 暂停下载任务的回调函数。

示例:

  downloadTask.suspend((err: BusinessError, result: boolean) => {
    if (err) {
      console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in pausing the download task.');
  });

restore9+

restore(): Promise&lt;boolean&gt;

重新启动暂停的下载任务,异步方法,使用promise形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;boolean&gt; 重新启动暂停的下载任务是否成功。

示例:

  downloadTask.restore().then((result: boolean) => {
    console.info('Succeeded in resuming the download task.')
  }).catch((err: BusinessError) => {
    console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
  });

restore9+

restore(callback: AsyncCallback&lt;boolean&gt;): void

重新启动暂停的下载任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 重新启动暂停的下载任务的回调函数。

示例:

  downloadTask.restore((err: BusinessError, result: boolean) => {
    if (err) {
      console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in resuming the download task.');
  });

remove(deprecated)

remove(): Promise&lt;boolean&gt;

移除下载的任务,异步方法,使用promise形式返回结果。

说明: 从API Version 9开始不再维护,建议使用delete9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;boolean&gt; 移除任务是否成功。

示例:

  downloadTask.remove().then((result) => {
    console.info('Succeeded in removing the download task.');
  }).catch ((err) => {
    console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
  });

remove(deprecated)

remove(callback: AsyncCallback&lt;boolean&gt;): void

移除下载的任务,异步方法,使用callback形式返回结果。

说明: 从API Version 9开始不再维护,建议使用delete9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;boolean&gt; 移除任务是否成功。

示例:

  downloadTask.remove((err, result)=>{
    if(err) {
      console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in removing the download task.');
  });

query(deprecated)

query(): Promise&lt;DownloadInfo&gt;

查询下载任务,异步方法,使用promise形式返回DownloadInfo里的信息。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用getTaskInfo9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;DownloadInfo&gt; 查询下载任务信息。

示例:

  downloadTask.query().then((downloadInfo) => {    
    console.info('Succeeded in querying the download task.')
  }) .catch((err) => {
    console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`)
  });

query(deprecated)

query(callback: AsyncCallback&lt;DownloadInfo&gt;): void

查询下载的任务,异步方法,使用callback形式返回结果。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用getTaskInfo9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;DownloadInfo&gt; 查询下载任务的回调函数。

示例:

  downloadTask.query((err, downloadInfo)=>{
    if(err) {
      console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
    } else {
      console.info('Succeeded in querying the download task.');
    }
  });

queryMimeType(deprecated)

queryMimeType(): Promise&lt;string&gt;

查询下载的任务的 MimeType,异步方法,使用promise形式返回结果。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用getTaskMimeType9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;string&gt; 查询下载任务的MimeType。

示例:

  downloadTask.queryMimeType().then((data) => {    
    console.info('Succeeded in querying the download MimeType.');
  }).catch((err) => {
    console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`)
  });

queryMimeType(deprecated)

queryMimeType(callback: AsyncCallback&lt;string&gt;): void;

查询下载的任务的 MimeType,异步方法,使用callback形式返回结果。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用getTaskMimeType9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;string&gt; 查询下载任务的MimeType的回调函数。

示例:

  downloadTask.queryMimeType((err, data)=>{
    if(err) {
      console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`);
    } else {
      console.info('Succeeded in querying the download mimeType.');
    }
  });

pause(deprecated)

pause(): Promise&lt;void&gt;

暂停下载任务,异步方法,使用promise形式返回结果。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用suspend9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;void&gt; 暂停下载任务是否成功。

示例:

  downloadTask.pause().then((result) => {    
    console.info('Succeeded in pausing the download task.');
  }).catch((err) => {
    console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
  });

pause(deprecated)

pause(callback: AsyncCallback&lt;void&gt;): void

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用suspend9+替代。

暂停下载任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;void&gt; 暂停下载任务的回调函数。

示例:

  downloadTask.pause((err, result)=>{
    if(err) {
      console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in pausing the download task.');
  });

resume(deprecated)

resume(): Promise&lt;void&gt;

重新启动暂停的下载任务,异步方法,使用promise形式返回结果。

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用restore9+替代。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型 说明
Promise&lt;void&gt; 重新启动暂停的下载任务是否成功。

示例:

  downloadTask.resume().then((result) => {
    console.info('Succeeded in resuming the download task.')
  }).catch((err) => {
    console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
  });

resume(deprecated)

resume(callback: AsyncCallback&lt;void&gt;): void

说明: 从API Version 7开始支持,从API Version 9开始不再维护,建议使用restore9+替代。

重新启动暂停的下载任务,异步方法,使用callback形式返回结果。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;void&gt; 重新启动暂停的下载任务的回调函数。

示例:

  downloadTask.resume((err, result)=>{
    if (err) {
      console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info('Succeeded in resuming the download task.');
  });

DownloadConfig

下载任务的配置信息。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

名称 类型 必填 说明
url string 资源地址。
header Object 添加要包含在下载请求中的HTTPS标志头。
开发者可以通过header的X-TLS-Version参数指定需要使用的TLS版本(如果不指定,则默认使用CURL_SSLVERSION_TLSv1_2版本,指定则使用指定版本。)
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
通过header的X-Cipher-List参数指定需要使用的密码套件(如果不指定,则默认使用安全密码套件,指定则使用指定密码套件。)
-1.2允许使用的密码套件白名单:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
-1.3允许使用的密码套件白名单:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
-1.3新增国密算法套:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3
enableMetered boolean 设置是否允许在按流量计费的连接下下载(默认使用false)。Wi-Fi为非计费网络,数据流量为计费网络。
-&nbsp;true:是
-&nbsp;false:否
enableRoaming boolean 设置是否允许在漫游网络中下载(默认使用false)。
-&nbsp;true:是
-&nbsp;false:否
description string 设置下载会话的描述。
filePath7+ string 设置下载路径。
-&nbsp;FA模型下使用context 获取应用存储路径,比如:`${featureAbility.getContext().getFilesDir()}/test.txt`,并将文件存储在此路径下。
-&nbsp;Stage模型下使用AbilityContext 类获取文件路径,比如:`${globalThis.abilityContext.tempDir}/test.txt`,并将文件存储在此路径下。
networkType number 设置允许下载的网络类型(默认使用NETWORK_MOBILE&NETWORK_WIFI)。
-&nbsp;NETWORK_MOBILE:0x00000001
-&nbsp;NETWORK_WIFI:0x00010000
title string 设置下载任务名称。
background9+ boolean 后台任务通知开关,开启后可在通知中显示下载状态(默认使用false)。

DownloadInfo7+

下载任务信息,getTaskInfo9+接口的回调参数。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

名称 类型 必填 说明
downloadId number 下载任务ID。
failedReason number 下载失败原因,可以是任何下载任务的错误码常量。
fileName string 下载的文件名。
filePath string 存储文件的URI。
pausedReason number 会话暂停的原因,可以是任何下载任务暂停原因常量。
status number 下载状态码,可以是任何下载任务状态码常量。
targetURI string 下载文件的URI。
downloadTitle string 下载任务名称。
downloadTotalBytes number 下载的文件的总大小(int&nbsp;bytes)。
description string 待下载任务的描述信息。
downloadedBytes number 实时下载大小(int&nbsp;&nbsp;bytes)。

Action10+

定义操作选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称 说明
DOWNLOAD 0 表示下载任务。
UPLOAD 1 表示上传任务。

Mode10+

定义模式选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称 说明
BACKGROUND 0 表示后台任务。
FOREGROUND 1 表示前端任务。

Network10+

定义网络选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称 说明
ANY 0 表示不限网络类型。
WIFI 1 表示无线网络。
CELLULAR 2 表示蜂窝数据网络。

FileSpec10+

表单项的文件信息。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
path string 文件路径位于调用方的缓存文件夹下的相对路径。
mimeType string 文件的mimetype通过文件名获取。
filename string 文件名,默认值通过路径获取。
extras Object 文件信息的附加内容。

FormItem10+

任务的表单项信息。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
name string 表单参数名。
value string |FileSpec |Array&lt;FileSpec&gt; 表单参数值。

Config10+

上传/下载任务的配置信息。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
action Action 任务操作选项。
-UPLOAD表示上传任务。
-DOWNLOAD表示下载任务。
url string 资源地址,其最大长度为2048个字符。
title string 任务标题,其最大长度为256个字符,默认值为空。
description string 任务的详细信息,其最大长度为1024个字符,默认值为空字符串。
mode Mode 任务模式,默认为后台任务。
-对于前端任务,有回调通知。
-对于后台任务,有系统通知、检测网络连接、恢复、自动重试功能。
overwrite boolean 下载过程中路径已存在时的解决方案选择,默认为false。
- true,覆盖已存在的文件。
- false,下载失败。
method string 上传或下载的HTTP标准方法,包括GET、POST和PUT,不区分大小写。
-上传时,使用PUT或POST,默认值为PUT。
-下载时,使用GET或POST,默认值为GET。
headers object 添加要包含在任务中的HTTP协议标志头。
-对于上传请求,默认的Content-Type为”multipart/form-data”。
-对于下载请求,默认的Content-Type为”application/json”。
data string |Array&lt;FormItem&gt; -下载时,data为字符串类型,通常使用json(object将被转换为json文本),默认为空。
-上传时,data是表单项数组Array&lt;FormItem&gt;,默认为空。
saveas string 保存下载文件的路径,包括如下两种:
-相对路径,如”./xxx/yyy/zzz.html”、”xxx/yyy/zzz.html”,位于调用方的缓存路径下。
-uri路径,如”datashare://bundle/xxx/yyy/zzz.html”,仅对具有访问url路径权限的应用开放。该功能暂不支持。
默认为相对路径,即下载至应用当前缓存路径下。
network Network 网络选项,当前支持无线网络WIFI和蜂窝数据网络CELLULAR,默认为ANY(WIFI或CELLULAR)。
metered boolean 是否允许在按流量计费的网络中工作,默认为false。
-true:是
-false:否
roaming boolean 是否允许在漫游网络中工作,默认为true。
-true:是
-false:否
retry boolean 是否为后台任务启用自动重试,仅应用于后台任务,默认为true。
-true:是
-false:否
redirect boolean 是否允许重定向,默认为true。
-true:是
-false:否
index number 任务的路径索引,通常用于任务断点续传,默认为0。
begins number 文件起点,通常用于断点续传。默认值为0,取值为闭区间。
-下载时,请求读取服务器开始下载文件时的起点位置(http协议中设置”Range”选项)。
-上传时,在上传开始时读取。
ends number 文件终点,通常用于断点续传。默认值为-1,取值为闭区间。
-下载时,请求读取服务器开始下载文件时的结束位置(http协议中设置”Range”选项)。
-上传时,在上传时结束读取。
gauge boolean 后台任务的过程进度通知策略,仅应用于后台任务,默认值为false。
-false:代表仅完成或失败的通知。
-true,发出每个进度已完成或失败的通知。
precise boolean -如果设置为true,在上传/下载无法获取文件大小时任务失败。
-如果设置为false,将文件大小设置为-1时任务继续。
默认值为false。
token string 当创建了一个带有token的任务后,token则为正常查询期间必须提供的,否则将无法通过查询进行检索。其最小为8个字节,最大为2048个字节。默认为空。
extras object 配置的附加功能,默认为空。

State10+

定义任务当前的状态。

系统能力: SystemCapability.Request.FileTransferAgent

名称 说明
INITIALIZED 0x00 通过配置信息(Config)创建初始化任务。
WAITING 0x10 表示任务缺少运行或重试的资源与网络状态不匹配。
RUNNING 0x20 表示正在处理的任务。
RETRYING 0x21 表示任务至少失败一次,现在正在再次处理中。
PAUSED 0x30 表示任务暂停,通常后续会恢复任务。
STOPPED 0x31 表示任务停止。
COMPLETED 0x40 表示任务完成。
FAILED 0x41 表示任务失败。
REMOVED 0x50 表示任务移除。

Progress10+

任务进度的数据结构。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
state State 任务当前的状态。
index number 任务中当前正在处理的文件索引。
processed number 任务中当前文件的已处理数据大小,单位为B。
sizes Array&lt;number&gt; 任务中文件的大小,单位为B。
extras object 交互的额外内容,例如来自服务器的响应的header和body。

Faults10+

定义任务失败的原因。

系统能力: SystemCapability.Request.FileTransferAgent

名称 说明
OTHERS 0xFF 表示其他故障。
DISCONNECTED 0x00 表示网络断开连接。
TIMEOUT 0x10 表示任务超时。
PROTOCOL 0x20 表示协议错误,例如:服务器内部错误(500)、无法处理的数据区间(416)等。
FSIO 0x40 表示文件系统io错误,例如打开/查找/读取/写入/关闭。

Filter10+

过滤条件。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
bundle string 指定应用程序的包名,仅对系统应用开放。
系统接口:此接口为系统接口。
before number 结束的Unix时间戳(毫秒),默认为调用时刻。
after number 开始的Unix时间戳(毫秒),默认值为调用时刻减24小时。
state State 指定任务的状态。
action Action 任务操作选项。
-UPLOAD表示上传任务。
-DOWNLOAD表示下载任务。
mode Mode 任务模式。
-FOREGROUND表示前端任务。
-BACKGROUND表示后台任务。

TaskInfo10+

查询结果的任务信息数据结构,提供普通查询和系统查询,两种字段的可见范围不同。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
uid string 应用程序的UID,仅用于系统查询。
系统接口:此接口为系统接口。
bundle string 应用程序的包名,仅用于系统查询。
系统接口:此接口为系统接口。
saveas string 保存下载文件的路径,包括如下两种:
-相对路径,如”./xxx/yyy/zzz.html”、”xxx/yyy/zzz.html”,位于调用方的缓存路径下。
-uri路径,如”datashare://bundle/xxx/yyy/zzz.html”,仅对具有访问url路径权限的应用开放。该功能暂不支持。
默认为相对路径,即下载至应用当前缓存路径下。
url string 任务的url。
- 通过request.agent.show10+request.agent.touch10+request.agent.query10+进行查询。其中,使用request.agent.query10+进行查询时会返回空字符串。
data string |Array&lt;FormItem&gt; 任务值。
- 通过request.agent.show10+request.agent.touch10+request.agent.query10+进行查询。其中,使用request.agent.query10+进行查询时会返回空字符串。
tid string 任务id。
title string 任务标题。
description string 任务描述。
action Action 任务操作选项。
-UPLOAD表示上传任务。
-DOWNLOAD表示下载任务。
mode Mode 指定任务模式。
-FOREGROUND表示前端任务。
-BACKGROUND表示后台任务。
mimeType string 任务配置中的mimetype。
progress Progress 任务的过程进度。
gauge boolean 后台任务的进度通知策略。
ctime number 创建任务的Unix时间戳(毫秒),由当前设备的系统生成。
说明:使用request.agent.search10+进行查询时,该值需处于[after,before]区间内才可正常查询到任务id,before和after信息详见Filter
mtime number 任务状态改变时的Unix时间戳(毫秒),由当前设备的系统生成。
retry boolean 任务的重试开关,仅应用于后台任务。
tries number 任务的尝试次数。
faults Faults 任务的失败原因。
-OTHERS表示其他故障。
-DISCONNECT表示网络断开连接。
-TIMEOUT表示任务超时。
-PROTOCOL表示协议错误。
-FSIO表示文件系统io错误。
reason string 等待/失败/停止/暂停任务的原因。
extras string 任务的额外部分。

Task10+

上传或下载任务。使用该方法前需要先获取Task对象,promise形式通过request.agent.create10+获取,callback形式通过request.agent.create10+获取。

属性

包括任务id和任务的配置信息。

系统能力: SystemCapability.Request.FileTransferAgent

名称 类型 必填 说明
tid string 任务id,在系统上是唯一的,由系统自动生成。
config Config 任务的配置信息。

on(‘progress’)10+

on(event: ‘progress’, callback: (progress: Progress) =&gt; void): void

订阅前端任务进度的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’progress’,表示任务进度。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOnTest",
    value: {
      filename: "taskOnTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOnTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOnTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    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.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('progress', createOnCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

on(‘completed’)10+

on(event: ‘completed’, callback: (progress: Progress) =&gt; void): void

订阅前端任务完成的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’completed’,表示任务完成。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOnTest",
    value: {
      filename: "taskOnTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOnTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOnTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    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 completed.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('completed', createOnCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

on(‘failed’)10+

on(event: ‘failed’, callback: (progress: Progress) =&gt; void): void

订阅前端任务失败的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’failed’,表示任务失败。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOnTest",
    value: {
      filename: "taskOnTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOnTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOnTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    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 failed.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('failed', createOnCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

off(‘progress’)10+

off(event: ‘progress’, callback?: (progress: Progress) =&gt; void): void

取消订阅前端任务进度的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’progress’,表示任务进度。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOffTest",
    value: {
      filename: "taskOffTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOffTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOffTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  let createOffCallback = (progress: request.agent.Progress) => {
    console.info('upload task progress.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('progress', createOffCallback);
    task.off('progress', createOffCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

off(‘completed’)10+

off(event: ‘completed’, callback?: (progress: Progress) =&gt; void): void

取消订阅前端任务完成的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’completed’,表示任务完成。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOffTest",
    value: {
      filename: "taskOffTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOffTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOffTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  let createOffCallback = (progress: request.agent.Progress) => {
    console.info('upload task completed.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('completed', createOffCallback);
    task.off('completed', createOffCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

off(‘failed’)10+

off(event: ‘failed’, callback?: (progress: Progress) =&gt; void): void

取消订阅前端任务失败的监听。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
event string 订阅的事件类型。
- 取值为’failed’,表示任务失败。
callback function 发生相关的事件时触发该回调方法,返回任务进度的数据结构。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "taskOffTest",
    value: {
      filename: "taskOffTest.avi",
      mimeType: "application/octet-stream",
      path: "./taskOffTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'taskOffTest',
    description: 'Sample code for event listening',
    mode: request.agent.Mode.FOREGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  let createOffCallback = (progress: request.agent.Progress) => {
    console.info('upload task failed.');
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.on('failed', createOffCallback);
    task.off('failed', createOffCallback);
    console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

start10+

start(callback: AsyncCallback&lt;void&gt;): void

启动任务,无法启动已初始化的任务。使用callback异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
callback function 回调函数,开启任务成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskStartTest',
    description: 'Sample code for start the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.start((err: BusinessError) => {
      if (err) {
        console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
        return;
      }
      console.info(`Succeeded in starting a download task.`);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

start10+

start(): Promise&lt;void&gt;

启动任务,无法启动已初始化的任务。使用Promise异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型 说明
Promise&lt;void&gt; Promise对象。无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskStartTest',
    description: 'Sample code for start the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.start().then(() => {
      console.info(`Succeeded in starting a download task.`);
    }).catch((err: BusinessError) => {
      console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

pause10+

pause(callback: AsyncCallback&lt;void&gt;): void

暂停任务,可以暂停正在等待/正在运行/正在重试的后台任务。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
callback function 回调函数,暂停任务成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900005 task mode error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskPauseTest',
    description: 'Sample code for pause the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.pause((err: BusinessError) => {
      if (err) {
        console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`);
        return;
      }
      console.info(`Succeeded in pausing a download task. `);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

pause10+

pause(): Promise&lt;void&gt;

暂停任务,可以暂停正在等待/正在运行/正在重试的后台任务。使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型 说明
Promise&lt;void&gt; Promise对象。无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900005 task mode error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskPauseTest',
    description: 'Sample code for pause the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.pause().then(() => {
      console.info(`Succeeded in pausing a download task. `);
    }).catch((err: BusinessError) => {
      console.error(`Failed to pause the upload task, Code: ${err.code}, message: ${err.message}`);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
  });

resume10+

resume(callback: AsyncCallback&lt;void&gt;): void

重新启动任务,可以恢复暂停的后台任务。使用callback异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
callback function 回调函数,重新启动任务成功,err为undefined,否则为错误对象

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900005 task mode error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskResumeTest',
    description: 'Sample code for resume the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.resume((err: BusinessError) => {
      if (err) {
        console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
        return;
      }
      console.info(`Succeeded in resuming a download task. `);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

resume10+

resume(): Promise&lt;void&gt;

重新启动任务,可以恢复暂停的后台任务。使用Promise异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型 说明
Promise&lt;void&gt; Promise对象。无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900005 task mode error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskResumeTest',
    description: 'Sample code for resume the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.resume().then(() => {
      console.info(`Succeeded in resuming a download task. `);
    }).catch((err: BusinessError) => {
      console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

stop10+

stop(callback: AsyncCallback&lt;void&gt;): void

停止任务,可以停止正在运行/正在等待/正在重试的任务。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
callback function 回调函数,停止任务成功,err为undefined,否则为错误对象

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskStopTest',
    description: 'Sample code for stop the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.stop((err: BusinessError) => {
      if (err) {
        console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
        return;
      }
      console.info(`Succeeded in stopping a download task. `);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

stop10+

stop(): Promise&lt;void&gt;

停止任务,可以停止正在运行/正在等待/正在重试的任务。使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型 说明
Promise&lt;void&gt; Promise对象。无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900007 task state error.

示例:

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: 'http://127.0.0.1',
    title: 'taskStopTest',
    description: 'Sample code for stop the download task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "GET",
    data: "",
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    task.stop().then(() => {
      console.info(`Succeeded in stopping a download task. `);
    }).catch((err: BusinessError) => {
      console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`);
    });
    console.info(`Succeeded in creating a download task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

request.agent.create10+

create(context: BaseContext, config: Config, callback: AsyncCallback&lt;Task&gt;): void

创建要上传或下载的任务,并将其排入队列,每个应用最多支持创建10个未完成的任务。使用callback异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
config Config 上传/下载任务的配置信息。
context BaseContext 基于应用程序的上下文。
callback AsyncCallback&lt;Task&gt; 回调函数,返回创建任务的配置信息。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400001 file operation error.
13400003 task service ability error.
21900004 application task queue full error.
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "createTest",
    value: {
      filename: "createTest.avi",
      mimeType: "application/octet-stream",
      path: "./createTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'createTest',
    description: 'Sample code for create task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => {
    if (err) {
      console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in creating a download task. result: ${task.config}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.agent.create10+

create(context: BaseContext, config: Config): Promise&lt;Task&gt;

创建要上传或下载的任务,并将其排入队列,每个应用最多支持创建10个未完成的任务。使用Promise异步回调。

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
context BaseContext 基于应用程序的上下文。
config Config 上传/下载任务的配置信息。

返回值:

类型 说明
Promise&lt;Task&gt; Promise对象。返回任务配置信息的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400001 file operation error.
13400003 task service ability error.
21900004 application task queue full error.
21900005 task mode error.

示例:

  let attachments: Array<request.agent.FormItem> = [{
    name: "createTest",
    value: {
      filename: "createTest.avi",
      mimeType: "application/octet-stream",
      path: "./createTest.avi",
    }
  }];
  let config: request.agent.Config = {
    action: request.agent.Action.UPLOAD,
    url: 'http://127.0.0.1',
    title: 'createTest',
    description: 'Sample code for create task',
    mode: request.agent.Mode.BACKGROUND,
    overwrite: false,
    method: "PUT",
    data: attachments,
    saveas: "./",
    network: request.agent.Network.CELLULAR,
    metered: false,
    roaming: true,
    retry: true,
    redirect: true,
    index: 0,
    begins: 0,
    ends: -1,
    gauge: false,
    precise: false,
    token: "it is a secret"
  };
  request.agent.create(getContext(), config).then((task: request.agent.Task) => {
    console.info(`Succeeded in creating a download task. result: ${task.config}`);
  }).catch((err) => {
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
  });

说明:

示例中context的获取方式请参见获取UIAbility的上下文信息

request.agent.remove10+

remove(id: string, callback: AsyncCallback&lt;void&gt;): void

移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。
callback AsyncCallback&lt;void&gt; 回调函数,删除指定任务成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.remove("123456", (err: BusinessError) => {
    if (err) {
      console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in creating a download task.`);
  });

request.agent.remove10+

remove(id: string): Promise&lt;void&gt;

移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止,使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。

返回值:

类型 说明
Promise&lt;void&gt; Promise对象。无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.remove("123456").then(() => {
    console.info(`Succeeded in removing a download task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`);
  });

request.agent.show10+

show(id: string, callback: AsyncCallback&lt;TaskInfo&gt;): void

根据任务id查询任务的详细信息。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。
callback AsyncCallback&lt;TaskInfo&gt; 回调函数,返回任务详细信息。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
    if (err) {
      console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in showing a upload task.`);
  });

request.agent.show10+

show(id: string): Promise&lt;TaskInfo&gt;

根据任务id查询任务的详细信息。使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。

返回值:

类型 说明
Promise&lt;TaskInfo&gt; Promise对象。返回任务详细信息的Promise对象。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => {
    console.info(`Succeeded in showing a upload task.`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`);
  });

request.agent.touch10+

touch(id: string, token: string, callback: AsyncCallback&lt;TaskInfo&gt;): void

根据任务id和token查询任务的详细信息。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。
token string 任务查询token。
callback AsyncCallback&lt;TaskInfo&gt; 回调函数,返回任务详细信息。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
    if (err) {
      console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in touching a upload task.`);
  });

request.agent.touch10+

touch(id: string, token: string): Promise&lt;TaskInfo&gt;

根据任务id和token查询任务的详细信息。使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
id string 任务id。
token string 任务查询token。

返回值:

类型 说明
Promise&lt;TaskInfo&gt; Promise对象。返回任务详细信息的Promise对象。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => {
    console.info(`Succeeded in touching a upload task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`);
  });

request.agent.search10+

search(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void

根据默认Filter过滤条件查找任务id。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
callback AsyncCallback&lt;Array&lt;string&gt;&gt; 回调函数,返回满足条件任务id。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.

示例:

  request.agent.search((err: BusinessError, data: Array<string>) => {
    if (err) {
      console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in searching a upload task. `);
  });

request.agent.search10+

search(filter: Filter, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void

根据Filter过滤条件查找任务id。使用callback异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
filter Filter 过滤条件。
callback AsyncCallback&lt;Array&lt;string&gt;&gt; 回调函数,返回满足条件任务id。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.

示例:

  let filter: request.agent.Filter = {
    bundle: "com.example.myapplication",
    action: request.agent.Action.UPLOAD,
    mode: request.agent.Mode.BACKGROUND
  }
  request.agent.search(filter, (err: BusinessError, data: Array<string>) => {
    if (err) {
      console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in searching a upload task. `);
  });

request.agent.search10+

search(filter?: Filter): Promise&lt;Array&lt;string&gt;&gt;

根据Filter过滤条件查找任务id。使用Promise异步回调。

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名 类型 必填 说明
filter Filter 过滤条件。

返回值:

类型 说明
Promise&lt;Array&lt;string&gt;&gt; Promise对象。返回满足条件任务id的Promise对象。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.

示例:

  let filter: request.agent.Filter = {
    bundle: "com.example.myapplication",
    action: request.agent.Action.UPLOAD,
    mode: request.agent.Mode.BACKGROUND
  }
  request.agent.search(filter).then((data: Array<string>) => {
    console.info(`Succeeded in searching a upload task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`);
  });

request.agent.query10+

query(id: string, callback: AsyncCallback&lt;TaskInfo&gt;): void

根据任务id查询任务的详细信息。使用callback异步回调。

需要权限:ohos.permission.DOWNLOAD_SESSION_MANAGER 或 ohos.permission.UPLOAD_SESSION_MANAGER

系统能力: SystemCapability.Request.FileTransferAgent

系统接口:此接口为系统接口。

参数:

参数名 类型 必填 说明
id string 任务id。
callback AsyncCallback&lt;TaskInfo&gt; 回调函数,返回任务详细信息。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.query("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => {
    if (err) {
      console.error(`Failed to query a upload task, Code: ${err.code}, message: ${err.message}`);
      return;
    }
    console.info(`Succeeded in querying a upload task. result: ${taskInfo.uid}`);
  });

request.agent.query10+

query(id: string): Promise&lt;TaskInfo&gt;

根据任务id查询任务的详细信息。使用Promise异步回调。

需要权限:ohos.permission.DOWNLOAD_SESSION_MANAGER 或 ohos.permission.UPLOAD_SESSION_MANAGER

系统能力: SystemCapability.Request.FileTransferAgent

系统接口:此接口为系统接口。

参数:

参数名 类型 必填 说明
id string 任务id。

返回值:

类型 说明
Promise&lt;TaskInfo&gt; Promise对象。返回任务详细信息的Promise对象。

错误码: 以下错误码的详细介绍请参见上传下载错误码

错误码ID 错误信息
13400003 task service ability error.
21900006 task not found error.

示例:

  request.agent.query("123456").then((taskInfo: request.agent.TaskInfo) => {
    console.info(`Succeeded in querying a upload task. result: ${taskInfo.uid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to query a upload task, Code: ${err.code}, message: ${err.message}`);
  });

你可能感兴趣的鸿蒙文章

harmony 鸿蒙接口

harmony 鸿蒙系统公共事件定义(待停用)

harmony 鸿蒙系统公共事件定义

harmony 鸿蒙开发说明

harmony 鸿蒙企业设备管理概述(仅对系统应用开放)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager模块)

harmony 鸿蒙@ohos.distributedBundle (分布式包管理)

harmony 鸿蒙@ohos.bundle (Bundle模块)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)

0  赞