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

2022-08-09 浏览 (1161)

@ohos.request (上传下载)

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

说明:

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

导入模块

import request from '@ohos.request';

常量

需要权限:ohos.permission.INTERNET

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

网络类型

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

名称参数类型数值说明
NETWORK_MOBILEnumber0x00000001使用蜂窝网络时允许下载的位标志。
NETWORK_WIFInumber0x00010000使用WLAN时允许下载的位标志。

下载任务的错误码

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

名称参数类型数值说明
ERROR_CANNOT_RESUME7+number0网络原因导致恢复下载失败。
ERROR_DEVICE_NOT_FOUND7+number1找不到SD卡等存储设备。
ERROR_FILE_ALREADY_EXISTS7+number2要下载的文件已存在,下载会话不能覆盖现有文件。
ERROR_FILE_ERROR7+number3文件操作失败。
ERROR_HTTP_DATA_ERROR7+number4HTTP传输失败。
ERROR_INSUFFICIENT_SPACE7+number5存储空间不足。
ERROR_TOO_MANY_REDIRECTS7+number6网络重定向过多导致的错误。
ERROR_UNHANDLED_HTTP_CODE7+number7无法识别的HTTP代码。
ERROR_UNKNOWN7+number8未知错误。
ERROR_OFFLINE9+number9网络未连接。
ERROR_UNSUPPORTED_NETWORK_TYPE9+number10网络类型不匹配。

下载任务暂停原因

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

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

下载任务状态码

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

名称参数类型数值说明
SESSION_SUCCESSFUL7+number0下载会话已完成。
SESSION_RUNNING7+number1下载会话正在进行中。
SESSION_PENDING7+number2正在调度下载会话。
SESSION_PAUSED7+number3下载会话已暂停。
SESSION_FAILED7+number4下载会话已失败,将不会重试。

request.uploadFile9+

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

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

返回值:

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

错误码:

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

错误码ID错误信息
13400002bad 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

参数:

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

错误码:

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

错误码ID错误信息
13400002bad 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

参数:

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

返回值:

类型说明
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

参数:

参数名类型必填说明
configUploadConfig上传的配置信息。
callbackAsyncCallback<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

参数:

参数名类型必填说明
typestring订阅的事件类型,取值为'progress'(上传的进度信息)。
callbackfunction上传进度的回调函数。

回调函数的参数

参数名类型必填说明
uploadedSizenumber当前已上传文件大小,单位为B。
totalSizenumber上传文件的总大小,单位为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

参数:

参数名类型必填说明
typestring订阅的事件类型,取值为'headerReceive'(接收响应头)。
callbackfunctionHTTP Response Header事件的回调函数。

回调函数的参数:

参数名类型必填说明
headerobjectHTTP 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

参数:

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

回调函数的参数

参数名类型必填说明
taskstatesArray<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) => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名类型必填说明
typestring取消订阅的事件类型,取值为'progress'(上传的进度信息)。
callbackfunction需要删除的上传任务进度的回调函数。
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) => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名类型必填说明
typestring取消订阅的事件类型,取值为'headerReceive'(接收响应头)。
callbackfunctionHTTP Response 需要删除的Header事件的回调函数。
header:HTTP Response 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<Array<TaskState>>): void;

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名类型必填说明
typestring订阅的事件类型,取值为'complete',表示上传任务完成;取值为'fail',表示上传任务失败。
callbackCallback<Array<TaskState>>需要删除的上传任务完成或失败的回调函数。
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<boolean>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

返回值:

类型说明
Promise<boolean>移除任务是否成功。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<boolean>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>移除任务的回调函数。

示例:

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<boolean>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

返回值:

类型说明
Promise<boolean>移除任务是否成功。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<boolean>): void

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Upload

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>移除任务的回调函数。

示例:

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。

名称类型必填说明
urlstring资源地址。
headerObject添加要包含在上传请求中的HTTP或HTTPS标志头。
methodstring请求方法:POST、PUT。缺省为POST。
indexnumber任务的路径索引,默认值为0。
beginsnumber在上传开始时读取的文件起点。默认值为0,取值为闭区间。
endsnumber在上传结束时读取的文件终点。默认值为-1,取值为闭区间。
filesArray<File>要上传的文件列表。请使用 multipart/form-data提交。
dataArray<RequestData>请求的表单数据。

TaskState9+

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

需要权限:ohos.permission.INTERNET

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

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

File

UploadConfig中的文件列表。

需要权限:ohos.permission.INTERNET

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

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

RequestData

UploadConfig中的表单数据。

需要权限:ohos.permission.INTERNET

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

名称类型必填说明
namestring表示表单元素的名称。
valuestring表示表单元素的值。

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

返回值:

类型说明
Promise<DownloadTask>返回下载任务。

错误码:

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

错误码ID错误信息
13400001file operation error.
13400002bad file path.
13400003task 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<DownloadTask>): void;

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
contextBaseContext基于应用程序的上下文。
configDownloadConfig下载的配置信息。
callbackAsyncCallback<DownloadTask>下载接口的回调函数。

错误码:

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

错误码ID错误信息
13400001file operation error.
13400002bad file path.
13400003task 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<DownloadTask>

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

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

返回值:

类型说明
Promise<DownloadTask>返回下载任务。

示例:

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<DownloadTask>): void

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

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
configDownloadConfig下载的配置信息。
callbackAsyncCallback<DownloadTask>下载接口的回调函数。

示例:

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) => void): void

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

说明:

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

回调函数的参数:

参数名类型必填说明
receivedSizenumber当前下载的进度,单位为B。
totalSizenumber下载文件的总大小,单位为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) => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
typestring取消订阅的事件类型,取值为'progress'(下载的进度信息)。
callbackfunction需要删除的下载任务进度的回调。
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:() => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

示例:

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?:() => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

示例:

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) => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
typestring订阅的事件类型,取值为'fail'(下载失败)。
callbackfunction下载失败的回调函数。

回调函数的参数:

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

示例:

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) => void): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

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

示例:

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

delete9+

delete(): Promise<boolean>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<boolean>移除任务是否成功。

示例:

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<boolean>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>移除任务是否成功。

示例:

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<DownloadInfo>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<DownloadInfo>查询下载任务信息。

示例:

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<DownloadInfo>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<DownloadInfo>查询下载任务的回调函数。

示例:

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<string>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<string>查询下载任务的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<string>): void;

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<string>查询下载任务的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<boolean>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<boolean>暂停下载任务是否成功。

示例:

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<boolean>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>暂停下载任务的回调函数。

示例:

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<boolean>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<boolean>重新启动暂停的下载任务是否成功。

示例:

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<boolean>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>重新启动暂停的下载任务的回调函数。

示例:

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<boolean>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<boolean>移除任务是否成功。

示例:

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<boolean>): void

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>移除任务是否成功。

示例:

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<DownloadInfo>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<DownloadInfo>查询下载任务信息。

示例:

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<DownloadInfo>): void

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<DownloadInfo>查询下载任务的回调函数。

示例:

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<string>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<string>查询下载任务的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<string>): void;

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<string>查询下载任务的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<void>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<void>暂停下载任务是否成功。

示例:

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<void>): void

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<void>暂停下载任务的回调函数。

示例:

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<void>

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

返回值:

类型说明
Promise<void>重新启动暂停的下载任务是否成功。

示例:

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<void>): void

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

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

参数:

参数名类型必填说明
callbackAsyncCallback<void>重新启动暂停的下载任务的回调函数。

示例:

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

名称类型必填说明
urlstring资源地址。
headerObject添加要包含在下载请求中的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
enableMeteredboolean设置是否允许在按流量计费的连接下下载(默认使用false)。Wi-Fi为非计费网络,数据流量为计费网络。
- true:是
- false:否
enableRoamingboolean设置是否允许在漫游网络中下载(默认使用false)。
- true:是
- false:否
descriptionstring设置下载会话的描述。
filePath7+string设置下载路径。
- FA模型下使用context 获取应用存储路径,比如:`${featureAbility.getContext().getFilesDir()}/test.txt`,并将文件存储在此路径下。
- Stage模型下使用AbilityContext 类获取文件路径,比如:`${globalThis.abilityContext.tempDir}/test.txt`,并将文件存储在此路径下。
networkTypenumber设置允许下载的网络类型(默认使用NETWORK_MOBILE&NETWORK_WIFI)。
- NETWORK_MOBILE:0x00000001
- NETWORK_WIFI:0x00010000
titlestring设置下载任务名称。
background9+boolean后台任务通知开关,开启后可在通知中显示下载状态(默认使用false)。

DownloadInfo7+

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.MiscServices.Download

名称类型必填说明
downloadIdnumber下载任务ID。
failedReasonnumber下载失败原因,可以是任何下载任务的错误码常量。
fileNamestring下载的文件名。
filePathstring存储文件的URI。
pausedReasonnumber会话暂停的原因,可以是任何下载任务暂停原因常量。
statusnumber下载状态码,可以是任何下载任务状态码常量。
targetURIstring下载文件的URI。
downloadTitlestring下载任务名称。
downloadTotalBytesnumber下载的文件的总大小(int bytes)。
descriptionstring待下载任务的描述信息。
downloadedBytesnumber实时下载大小(int  bytes)。

Action10+

定义操作选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称说明
DOWNLOAD0表示下载任务。
UPLOAD1表示上传任务。

Mode10+

定义模式选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称说明
BACKGROUND0表示后台任务。
FOREGROUND1表示前端任务。

Network10+

定义网络选项。

系统能力: SystemCapability.Request.FileTransferAgent

名称说明
ANY0表示不限网络类型。
WIFI1表示无线网络。
CELLULAR2表示蜂窝数据网络。

FileSpec10+

表单项的文件信息。

系统能力: SystemCapability.Request.FileTransferAgent

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

FormItem10+

任务的表单项信息。

系统能力: SystemCapability.Request.FileTransferAgent

名称类型必填说明
namestring表单参数名。
valuestring |FileSpec |Array<FileSpec>表单参数值。

Config10+

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

系统能力: SystemCapability.Request.FileTransferAgent

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

State10+

定义任务当前的状态。

系统能力: SystemCapability.Request.FileTransferAgent

名称说明
INITIALIZED0x00通过配置信息(Config)创建初始化任务。
WAITING0x10表示任务缺少运行或重试的资源与网络状态不匹配。
RUNNING0x20表示正在处理的任务。
RETRYING0x21表示任务至少失败一次,现在正在再次处理中。
PAUSED0x30表示任务暂停,通常后续会恢复任务。
STOPPED0x31表示任务停止。
COMPLETED0x40表示任务完成。
FAILED0x41表示任务失败。
REMOVED0x50表示任务移除。

Progress10+

任务进度的数据结构。

系统能力: SystemCapability.Request.FileTransferAgent

名称类型必填说明
stateState任务当前的状态。
indexnumber任务中当前正在处理的文件索引。
processednumber任务中当前文件的已处理数据大小,单位为B。
sizesArray<number>任务中文件的大小,单位为B。
extrasobject交互的额外内容,例如来自服务器的响应的header和body。

Faults10+

定义任务失败的原因。

系统能力: SystemCapability.Request.FileTransferAgent

名称说明
OTHERS0xFF表示其他故障。
DISCONNECTED0x00表示网络断开连接。
TIMEOUT0x10表示任务超时。
PROTOCOL0x20表示协议错误,例如:服务器内部错误(500)、无法处理的数据区间(416)等。
FSIO0x40表示文件系统io错误,例如打开/查找/读取/写入/关闭。

Filter10+

过滤条件。

系统能力: SystemCapability.Request.FileTransferAgent

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

TaskInfo10+

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

系统能力: SystemCapability.Request.FileTransferAgent

名称类型必填说明
uidstring应用程序的UID,仅用于系统查询。
系统接口:此接口为系统接口。
bundlestring应用程序的包名,仅用于系统查询。
系统接口:此接口为系统接口。
saveasstring保存下载文件的路径,包括如下两种:
-相对路径,如"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html",位于调用方的缓存路径下。
-uri路径,如"datashare://bundle/xxx/yyy/zzz.html",仅对具有访问url路径权限的应用开放。该功能暂不支持。
默认为相对路径,即下载至应用当前缓存路径下。
urlstring任务的url。
- 通过request.agent.show10+request.agent.touch10+request.agent.query10+进行查询。其中,使用request.agent.query10+进行查询时会返回空字符串。
datastring |Array<FormItem>任务值。
- 通过request.agent.show10+request.agent.touch10+request.agent.query10+进行查询。其中,使用request.agent.query10+进行查询时会返回空字符串。
tidstring任务id。
titlestring任务标题。
descriptionstring任务描述。
actionAction任务操作选项。
-UPLOAD表示上传任务。
-DOWNLOAD表示下载任务。
modeMode指定任务模式。
-FOREGROUND表示前端任务。
-BACKGROUND表示后台任务。
mimeTypestring任务配置中的mimetype。
progressProgress任务的过程进度。
gaugeboolean后台任务的进度通知策略。
ctimenumber创建任务的Unix时间戳(毫秒),由当前设备的系统生成。
说明:使用request.agent.search10+进行查询时,该值需处于[after,before]区间内才可正常查询到任务id,before和after信息详见Filter
mtimenumber任务状态改变时的Unix时间戳(毫秒),由当前设备的系统生成。
retryboolean任务的重试开关,仅应用于后台任务。
triesnumber任务的尝试次数。
faultsFaults任务的失败原因。
-OTHERS表示其他故障。
-DISCONNECT表示网络断开连接。
-TIMEOUT表示任务超时。
-PROTOCOL表示协议错误。
-FSIO表示文件系统io错误。
reasonstring等待/失败/停止/暂停任务的原因。
extrasstring任务的额外部分。

Task10+

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

属性

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

系统能力: SystemCapability.Request.FileTransferAgent

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

on('progress')10+

on(event: 'progress', callback: (progress: Progress) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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) => void): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
21900005task 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<void>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900007task 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<void>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型说明
Promise<void>Promise对象。无返回结果的Promise对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900007task 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<void>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900005task mode error.
21900007task 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<void>

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

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型说明
Promise<void>Promise对象。无返回结果的Promise对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900005task mode error.
21900007task 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<void>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900005task mode error.
21900007task 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<void>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型说明
Promise<void>Promise对象。无返回结果的Promise对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900005task mode error.
21900007task 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<void>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900007task 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<void>

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

系统能力: SystemCapability.Request.FileTransferAgent

返回值:

类型说明
Promise<void>Promise对象。无返回结果的Promise对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900007task 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<Task>): void

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
configConfig上传/下载任务的配置信息。
contextBaseContext基于应用程序的上下文。
callbackAsyncCallback<Task>回调函数,返回创建任务的配置信息。

错误码:

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

错误码ID错误信息
13400001file operation error.
13400003task service ability error.
21900004application task queue full error.
21900005task 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<Task>

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

需要权限:ohos.permission.INTERNET

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

返回值:

类型说明
Promise<Task>Promise对象。返回任务配置信息的Promise对象。

错误码:

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

错误码ID错误信息
13400001file operation error.
13400003task service ability error.
21900004application task queue full error.
21900005task 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<void>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
idstring任务id。
callbackAsyncCallback<void>回调函数,删除指定任务成功,err为undefined,否则为错误对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<void>

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

返回值:

类型说明
Promise<void>Promise对象。无返回结果的Promise对象。

错误码:

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<TaskInfo>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
idstring任务id。
callbackAsyncCallback<TaskInfo>回调函数,返回任务详细信息。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<TaskInfo>

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

返回值:

类型说明
Promise<TaskInfo>Promise对象。返回任务详细信息的Promise对象。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<TaskInfo>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
idstring任务id。
tokenstring任务查询token。
callbackAsyncCallback<TaskInfo>回调函数,返回任务详细信息。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<TaskInfo>

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

返回值:

类型说明
Promise<TaskInfo>Promise对象。返回任务详细信息的Promise对象。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<Array<string>>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
callbackAsyncCallback<Array<string>>回调函数,返回满足条件任务id。

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

错误码ID错误信息
13400003task 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<Array<string>>): void

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

参数名类型必填说明
filterFilter过滤条件。
callbackAsyncCallback<Array<string>>回调函数,返回满足条件任务id。

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

错误码ID错误信息
13400003task 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<Array<string>>

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

系统能力: SystemCapability.Request.FileTransferAgent

参数:

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

返回值:

类型说明
Promise<Array<string>>Promise对象。返回满足条件任务id的Promise对象。

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

错误码ID错误信息
13400003task 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<TaskInfo>): void

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

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

系统能力: SystemCapability.Request.FileTransferAgent

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

参数:

参数名类型必填说明
idstring任务id。
callbackAsyncCallback<TaskInfo>回调函数,返回任务详细信息。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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<TaskInfo>

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

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

系统能力: SystemCapability.Request.FileTransferAgent

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

参数:

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

返回值:

类型说明
Promise<TaskInfo>Promise对象。返回任务详细信息的Promise对象。

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

错误码ID错误信息
13400003task service ability error.
21900006task 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 (企业设备管理扩展能力)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/aff66ae331104441b3eca4833da60503