当前仓库属于关闭状态,部分功能使用受限,详情请查阅 仓库状态说明
1.4K Star 7.4K Fork 8.2K

OpenHarmony/docs
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.config
.gitee
docker
en
application-dev
IDL
accessibility
ads-service
ai
application-models
application-test
arkts-utils
basic-services
calendarmanager
connectivity
contacts
database
device-usage-statistics
device
dfx
displaymanager
distributedservice
enterprise-device-management
faqs
ffrt
file-management
form
graphics
graphics3d
inputmethod
internationalization
ipc
mdm
media
napi
network
notification
onlyfortest/reference
performance
public_sys-resources
quick-start
reference
apis-ability-kit
apis-accessibility-kit
apis-ads-kit
apis-arkdata
apis-arkgraphics2d
apis-arkgraphics3d
apis-arkts
apis-arkui
apis-arkweb
apis-asset-store-kit
apis-audio-kit
apis-avcodec-kit
apis-avsession-kit
apis-backgroundtasks-kit
apis-basic-services-kit
common_event
Readme-EN.md
_device_info.md
_init_sync.md
_o_h___print.md
_os_account.md
_pasteboard.md
_print___margin.md
_print___page_size.md
_print___print_attributes.md
_print___print_doc_callback.md
_print___range.md
_time_service.md
c-apis-scan.md
capi-common-event.md
capi-oh-pasteboard-err-code-h.md
capi-oh-pasteboard-h.md
capi-os-account-common-h.md
capi-os-account-h.md
capi-osaccount.md
capi-pasteboard-getdataparams.md
capi-pasteboard-oh-pasteboard.md
capi-pasteboard-oh-pasteboardobserver.md
capi-pasteboard-progressinfo.md
capi-pasteboard.md
deviceinfo_8h.md
errorcode-CommonEventService.md
errorcode-account.md
errorcode-battery-info.md
errorcode-batteryStatistics.md
errorcode-brightness.md
errorcode-deviceAttest.md
errorcode-intelligentVoice.md
errorcode-pasteboard.md
errorcode-power.md
errorcode-print.md
errorcode-request.md
errorcode-runninglock.md
errorcode-screenlock.md
errorcode-settings.md
errorcode-system-parameterV9.md
errorcode-thermal.md
errorcode-time.md
errorcode-update.md
errorcode-usb.md
errorcode-zlib.md
init__sync_8h.md
js-apis-WallpaperExtensionAbility-sys.md
js-apis-app-ability-PrintExtensionAbility-sys.md
js-apis-app-ability-PrintExtensionAbility.md
js-apis-appAccount.md
js-apis-application-StaticSubscriberExtensionContext-sys.md
js-apis-application-staticSubscriberExtensionAbility-sys.md
js-apis-base.md
js-apis-battery-info-sys.md
js-apis-battery-info.md
js-apis-batteryStatistics-sys.md
js-apis-brightness-sys.md
js-apis-charger-sys.md
js-apis-commonEvent-sys.md
js-apis-commonEvent.md
js-apis-commonEventManager-sys.md
js-apis-commonEventManager.md
js-apis-configPolicy-sys.md
js-apis-customization-customConfig.md
js-apis-date-time.md
js-apis-device-info.md
js-apis-deviceAttest-sys.md
js-apis-distributed-account-sys.md
js-apis-distributed-account.md
js-apis-emitter.md
js-apis-inner-commonEvent-commonEventData.md
js-apis-inner-commonEvent-commonEventPublishData.md
js-apis-inner-commonEvent-commonEventSubscribeInfo.md
js-apis-inner-commonEvent-commonEventSubscriber.md
js-apis-intelligentVoice-sys.md
js-apis-osAccount-sys.md
js-apis-osAccount.md
js-apis-pasteboard.md
js-apis-power-sys.md
js-apis-power.md
js-apis-print-sys.md
js-apis-print.md
js-apis-request-cacheDownload.md
js-apis-request-sys.md
js-apis-request.md
js-apis-resourceschedule-systemload.md
js-apis-runninglock.md
js-apis-screen-lock-sys.md
js-apis-screen-lock.md
js-apis-serialManager-sys.md
js-apis-serialManager.md
js-apis-settings-sys.md
js-apis-settings.md
js-apis-system-battery.md
js-apis-system-brightness.md
js-apis-system-capability-sys.md
js-apis-system-date-time-sys.md
js-apis-system-device.md
js-apis-system-parameter-sys.md
js-apis-system-parameterEnhance-sys.md
js-apis-system-request.md
js-apis-system-time.md
js-apis-system-timer-sys.md
js-apis-thermal.md
js-apis-update-sys.md
js-apis-usb-deprecated-sys.md
js-apis-usb-deprecated.md
js-apis-usbManager-sys.md
js-apis-usbManager.md
js-apis-wallpaper-sys.md
js-apis-wallpaper.md
js-apis-zlib.md
oh__batteryinfo.md
oh__pasteboard_8h.md
oh__pasteboard__err__code_8h.md
oh_commonevent_8h.md
oh_commonevent_support_8h.md
ohbattery__info_8h.md
ohprint_8h.md
os__account_8h.md
os__account__common_8h.md
time__service_8h.md
apis-calendar-kit
apis-camera-kit
apis-connectivity-kit
apis-contacts-kit
apis-core-file-kit
apis-crypto-architecture-kit
apis-data-protection-kit
apis-device-certificate-kit
apis-distributedservice-kit
apis-driverdevelopment-kit
apis-drm-kit
apis-ffrt-kit
apis-form-kit
apis-image-kit
apis-ime-kit
apis-input-kit
apis-ipc-kit
apis-localization-kit
apis-location-kit
apis-mdm-kit
apis-media-kit
apis-media-library-kit
apis-mindspore-lite-kit
apis-multimodalawareness-kit
apis-network-kit
apis-neural-network-runtime-kit
apis-notification-kit
apis-performance-analysis-kit
apis-sensor-service-kit
apis-telephony-kit
apis-test-kit
apis-universal-keystore-kit
apis-user-authentication-kit
common
figures
native-lib
Readme-EN.md
development-intro-api.md
errorcode-universal.md
litewearable-syscap-list.md
phone-syscap-list.md
syscap-list.md
syscap.md
tablet-syscap-list.md
tv-syscap-list.md
wearable-syscap-list.md
security
task-management
telephony
tools
ui
web
webgl
windowmanager
Readme-EN.md
application-dev-guide-for-gitee.md
application-dev-guide.md
website.md
contribute
design
device-dev
figures
readme
release-notes
third-party-components
Legal-Notices.md
OpenHarmony-Overview.md
glossary.md
readme.md
website.md
zh-cn
.gitattributes
.gitignore
CODEOWNERS
DCO.txt
LICENSE
OAT.xml
README.md
README_zh.md
image.png
克隆/下载
js-apis-request.md 226.97 KB
一键复制 编辑 原始数据 按行查看 历史
胡芷珊 提交于 9天前 . update docs

@ohos.request (Upload and Download)

The request module provides applications with basic upload, download, and background transmission agent capabilities.

NOTE

The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

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

Constants

System capability: SystemCapability.MiscServices.Download

NOTE

Network type: set networkType in DownloadConfig to specify the network type for the download service.

Download error codes: values of err in the callback of on('fail')7+ and the values of the failedReason field returned by getTaskInfo9+.

Causes of download pause: values of pausedReason returned by getTaskInfo9+.

Download task status code: values of status returned by getTaskInfo9+.

Name Type Value Description
EXCEPTION_PERMISSION9+ number 201 (Universal error codes) Permission verification failed.
EXCEPTION_PARAMCHECK9+ number 401 (Universal error codes) Parameter check failed.
EXCEPTION_UNSUPPORTED9+ number 801 (Universal error codes) The device does not support this API.
EXCEPTION_FILEIO9+ number 13400001 (Specific error codes) Abnormal file operation.
EXCEPTION_FILEPATH9+ number 13400002 (Specific error codes) Abnormal file path.
EXCEPTION_SERVICE9+ number 13400003 (Specific error codes) Abnormal service.
EXCEPTION_OTHERS9+ number 13499999 (Specific error codes) Other errors.
NETWORK_MOBILE6+ number 0x00000001 (Network type) Bit flag download allowed on a mobile network.
NETWORK_WIFI6+ number 0x00010000 (Network type) Bit flag download allowed on a WLAN.
ERROR_CANNOT_RESUME7+ number 0 (Download error codes) Failure to resume the download due to network errors.
ERROR_DEVICE_NOT_FOUND7+ number 1 (Download error codes) Failure to find a storage device such as a memory card.
ERROR_FILE_ALREADY_EXISTS7+ number 2 (Download error codes) Failure to download the file because it already exists.
ERROR_FILE_ERROR7+ number 3 (Download error codes) File operation failed.
ERROR_HTTP_DATA_ERROR7+ number 4 (Download error codes) HTTP transmission failed.
ERROR_INSUFFICIENT_SPACE7+ number 5 (Download error codes) Insufficient storage space.
ERROR_TOO_MANY_REDIRECTS7+ number 6 (Download error codes) Error caused by too many network redirections.
ERROR_UNHANDLED_HTTP_CODE7+ number 7 (Download error codes) Unidentified HTTP code.
ERROR_UNKNOWN7+ number 8 (Download error codes) Unknown error.
In API version 12 or earlier, only serial connection to the IP addresses associated with the specified domain name is supported, and the connection time for a single IP address is not controllable. If the first IP address returned by the DNS is blocked, a handshake timeout may occur, leading to an ERROR_UNKNOWN error.
ERROR_OFFLINE9+ number 9 (Download error codes) No network connection.
ERROR_UNSUPPORTED_NETWORK_TYPE9+ number 10 (Download error codes) Network type mismatch.
PAUSED_QUEUED_FOR_WIFI7+ number 0 (Causes of download pause) Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed for a mobile network session.
PAUSED_WAITING_FOR_NETWORK7+ number 1 (Causes of download pause) Download paused due to a network connection problem,
for example, network disconnection.
PAUSED_WAITING_TO_RETRY7+ number 2 (Causes of download pause) Download paused due to network error and then retried.
PAUSED_BY_USER9+ number 3 (Causes of download pause) The user paused the session.
PAUSED_UNKNOWN7+ number 4 (Causes of download pause) Download paused due to unknown reasons.
SESSION_SUCCESSFUL7+ number 0 (Download task status codes) Successful download.
SESSION_RUNNING7+ number 1 (Download task status codes) Download in progress.
SESSION_PENDING7+ number 2 (Download task status codes) Download pending.
SESSION_PAUSED7+ number 3 (Download task status codes) Download paused.
SESSION_FAILED7+ number 4 (Download task status codes) Download failure without retry.

request.uploadFile9+

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

Uploads a file. This API uses a promise to return the result. HTTP is supported. You can use on('complete'|'fail')9+ to obtain the upload success or error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
config UploadConfig Yes Upload configurations.

Return value

Type Description
Promise<UploadTask> Promise used to return the UploadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400002 File path not supported or invalid.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let uploadTask: request.UploadTask;
let uploadConfig: request.UploadConfig = {
  url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol.
  data: [{ name: "name123", value: "123" }],
};
try {
  request.uploadFile(context, 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)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.uploadFile9+

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

Uploads a file. This API uses an asynchronous callback to return the result. HTTP is supported. You can use on('complete'|'fail')9+ to obtain the upload success or error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
config UploadConfig Yes Upload configurations.
callback AsyncCallback<UploadTask> Yes Callback used to return the UploadTask object. If the operation is successful, err is undefined, and data is the UploadTask object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400002 File path not supported or invalid.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let uploadTask: request.UploadTask;
let uploadConfig: request.UploadConfig = {
  url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol.
  data: [{ name: "name123", value: "123" }],
};
try {
  request.uploadFile(context, 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)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.upload(deprecated)

upload(config: UploadConfig): Promise<UploadTask>

Uploads files. This API uses a promise to return the result.

Model restriction: This API can be used only in the FA model.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use request.uploadFile9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
config UploadConfig Yes Upload configurations.

Return value

Type Description
Promise<UploadTask> Promise used to return the UploadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

let uploadTask;
let uploadConfig = {
  url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol.
  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

Uploads files. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the FA model.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use request.uploadFile9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
config UploadConfig Yes Upload configurations.
callback AsyncCallback<UploadTask> Yes Callback used to return the UploadTask object. If the operation is successful, err is undefined, and data is the UploadTask object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

let uploadTask;
let uploadConfig = {
  url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server.
  header: { 'Accept': '*/*' },
  method: "POST",
  files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol.
  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

Implements file uploads. Before using any APIs of this class, you must obtain an UploadTask object through request.uploadFile9+ in promise mode or request.uploadFile9+ in callback mode.

on('progress')

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

Subscribes to upload progress events. This API uses an asynchronous callback to return the result.

NOTE

To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
- 'progress': upload progress.
callback function Yes Callback used to return the size of the uploaded file and the total size of the file to upload.

Parameters of the callback function

Name Type Mandatory Description
uploadedSize number Yes Size of the uploaded files, in bytes.
totalSize number Yes Total size of the files to upload, in bytes.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

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

Subscribes to HTTP response events for the upload task.This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
- 'headerReceive': The HTTP request receives a response.
callback function Yes Callback used to return the response content.

Parameters of the callback function

Name Type Mandatory Description
header object Yes HTTP response.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

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

Subscribes to upload completion or failure events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
callback Callback<Array<TaskState>> Yes Callback used to return the result.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

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

Unsubscribes from upload progress events.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'progress': upload progress.
callback function No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Parameters of the callback function

Name Type Mandatory Description
uploadedSize number Yes Size of the uploaded files, in bytes.
totalSize number Yes Total size of the files to upload, in bytes.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

let upProgressCallback1 = (uploadedSize: number, totalSize: number) => {
  console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize);
};
let upProgressCallback2 = (uploadedSize: number, totalSize: number) => {
  console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize);
};
uploadTask.on('progress', upProgressCallback1);
uploadTask.on('progress', upProgressCallback2);
// Unsubscribe from upProgressCallback1.
uploadTask.off('progress', upProgressCallback1);
// Unsubscribe from all callbacks of upload progress events.
uploadTask.off('progress');

off('headerReceive')7+

off(type: 'headerReceive', callback?: (header: object) => void): void

Unsubscribes from HTTP response events for the upload task.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'headerReceive': The HTTP request receives a response.
callback function No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Parameters of the callback function

Name Type Mandatory Description
header object Yes HTTP response.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

let headerCallback1 = (header: object) => {
  console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`);
};
let headerCallback2 = (header: object) => {
  console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`);
};
uploadTask.on('headerReceive', headerCallback1);
uploadTask.on('headerReceive', headerCallback2);
// Unsubscribe from headerCallback1.
uploadTask.off('headerReceive', headerCallback1);
// Unsubscribe from all callbacks of the HTTP header events for the upload task.
uploadTask.off('headerReceive');

off('complete' | 'fail')9+

off(type: 'complete' | 'fail', callback?: Callback<Array<TaskState>>): void

Unsubscribes from upload completion or failure events.

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'complete': upload task completion.
- 'fail': upload task failure.
callback Callback<Array<TaskState>> No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

let upCompleteCallback1 = (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]));
  }
};
let upCompleteCallback2 = (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.on('complete', upCompleteCallback1);
uploadTask.on('complete', upCompleteCallback2);
// Unsubscribe from headerCallback1.
uploadTask.off('complete', upCompleteCallback1);
// Unsubscribe from all callbacks of the upload completion events.
uploadTask.off('complete');

let upFailCallback1 = (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]));
  }
};
let upFailCallback2 = (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.on('fail', upFailCallback1);
uploadTask.on('fail', upFailCallback2);
// Unsubscribe from headerCallback1.
uploadTask.off('fail', upFailCallback1);
// Unsubscribe from all callbacks of the upload failure events.
uploadTask.off('fail');

delete9+

delete(): Promise<boolean>

Deletes this upload task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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}`);
});

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

delete9+

delete(callback: AsyncCallback<boolean>): void

Deletes this upload task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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.');
});

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

remove(deprecated)

remove(): Promise<boolean>

Removes this upload task. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

Removes this upload task. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Upload

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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}`);
  }
});

UploadConfig6+

Describes the configuration of an upload task.

System capability: SystemCapability.MiscServices.Upload

Name Type Mandatory Description
url string Yes Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; since API version 15, the value contains a maximum of 8192 characters. Intercepting HTTP is supported.
header Object Yes HTTP or HTTPS header added to an upload request.
method string Yes HTTP request method. The value can be POST or PUT. The default value is POST. Use POST to add resources and PUT to modify resources.
index11+ number No Path index of the task. The default value is 0.
begins11+ number No Start point of the file read when the upload task begins. The default value is 0. The value is a closed interval, indicating that the file is read from the beginning.
ends11+ number No End point of the file read when the upload task is complete. The default value is -1. The value is a closed interval, indicating that the file is read till the end.
files Array<File> Yes List of files to upload. The files are submitted in multipart/form-data format.
data Array<RequestData> Yes Form data in the request body.

TaskState9+

Implements a TaskState object, which is the callback parameter of the on('complete' | 'fail')9+ and off('complete' | 'fail')9+ APIs.

System capability: SystemCapability.MiscServices.Upload

Name Type Mandatory Description
path string Yes File path.
responseCode number Yes Return value of an upload task. The value 0 means that the task is successful, and other values means that the task fails. For details about the task result, see message.
You are advised to create an upload task by using request.agent.create10+ and handle exceptions based on standard error codes.
message string Yes Description of the upload task result.

The following table describes the enum values of responseCode.

Result Code Description
0 uploaded success.
5 Task suspended or stopped proactively.
6 Foreground task stopped. The reason is that the application, to which the task belongs, is switched to the background or terminated. Check the application status.
7 No network connection. Check whether the device is connected to the network.
8 Network mismatch. Check whether the current network type matches the network type required by the task.
10 Failed to create the HTTP request. Verify the parameters or try again.
12 Request timeout. Verify the parameter configuration or the network connection, or try again.
13 Connection failed. Verify the parameter configuration or the network connection, or try again.
14 Request failed. Verify the parameter configuration or the network connection, or try again.
15 Upload failed. Verify the parameter configuration or the network connection, or try again.
16 Redirection failed. Verify the parameter configuration or the network connection, or try again.
17 Protocol error. The server returns a 4XX or 5XX status code. Verify the parameter configuration and try again.
20 Other errors. Verify the parameter configuration or the network connection, or try again.

File

Defines the file list in UploadConfig6+.

System capability: SystemCapability.MiscServices.Download

Name Type Mandatory Description
filename string Yes File name in the header when multipart is used.
name string Yes Name of a form item when multipart is used. The default value is file.
uri string Yes Local path for storing files.
Only internal://cache/ is supported, that is, context.cacheDir of the caller (namely, cache directory of the input context).
Example: internal://cache/path/to/file.txt.
type string Yes Type of the file content. By default, the type is obtained based on the extension of the file name or URI.

RequestData

Defines the form data in UploadConfig6+.

System capability: SystemCapability.MiscServices.Download

Name Type Mandatory Description
name string Yes Name of a form element.
value string Yes Value of a form element.

request.downloadFile9+

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

Downloads a file. This API uses a promise to return the result. HTTP is supported. You can use on('complete'|'pause'|'remove')7+ to obtain the download task state, which can be completed, paused, or removed. You can also use on('fail')7+ to obtain the task download error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
config DownloadConfig Yes Download configuration.

Return value

Type Description
Promise<DownloadTask> Promise used to return the DownloadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400001 Invalid file or file system error.
13400002 File path not supported or invalid.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
     let downloadTask: request.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)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.downloadFile9+

downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void

Downloads a file. This API uses an asynchronous callback to return the result. HTTP is supported. You can use on('complete'|'pause'|'remove')7+ to obtain the download task state, which can be completed, paused, or removed. You can also use on('fail')7+ to obtain the task download error information.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
config DownloadConfig Yes Download configuration.
callback AsyncCallback<DownloadTask> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the DownloadTask object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400001 Invalid file or file system error.
13400002 File path not supported or invalid.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, {
    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;
    }
    let downloadTask: request.DownloadTask = data;
  });
} catch (err) {
  console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
}

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.download(deprecated)

download(config: DownloadConfig): Promise<DownloadTask>

Download files. This API uses a promise to return the result.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use request.downloadFile9+ instead.

Model restriction: This API can be used only in the FA model.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
config DownloadConfig Yes Download configuration.

Return value

Type Description
Promise<DownloadTask> Promise used to return the DownloadTask object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

let downloadTask;
// Replace the URL with the HTTP address of the real server.
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

Downloads files. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 6 and deprecated since API version 9. You are advised to use request.downloadFile9+ instead.

Model restriction: This API can be used only in the FA model.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
config DownloadConfig Yes Download configuration.
callback AsyncCallback<DownloadTask> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the DownloadTask object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

let downloadTask;
// Replace the URL with the HTTP address of the real server.
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

Implements file downloads. Before using any APIs of this class, you must obtain a DownloadTask object through request.downloadFile9+ in promise mode or request.downloadFile9+ in callback mode.

on('progress')

on(type: 'progress', callback: (receivedSize: number, totalSize: number) => void): void

Subscribes to download progress events. This API uses an asynchronous callback to return the result.

NOTE

To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
- 'progress': download progress.
callback function Yes Callback used to return the size of the uploaded file and the total size of the file to upload.

Parameters of the callback function

Name Type Mandatory Description
receivedSize number Yes Current download progress, in bytes.
totalSize number Yes Total size of the files to download, in bytes. If the server uses the chunk mode for data transmission and the total file size cannot be obtained from the request header, the value of totalSize is treated as -1.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let progressCallback = (receivedSize: number, totalSize: number) => {
      console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
    };
    downloadTask.on('progress', progressCallback);
  }).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)}`);
}

off('progress')

off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void

Unsubscribes from download progress events.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'progress': download progress.
callback function No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Parameters of the callback function

Name Type Mandatory Description
receivedSize number Yes Current download progress, in bytes.
totalSize number Yes Total size of the files to download, in bytes. If the server uses the chunk mode for data transmission and the total file size cannot be obtained from the request header, the value of totalSize is treated as -1.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let progressCallback1 = (receivedSize: number, totalSize: number) => {
      console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize);
    };
    let progressCallback2 = (receivedSize: number, totalSize: number) => {
      console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize);
    };
    downloadTask.on('progress', progressCallback1);
    downloadTask.on('progress', progressCallback2);
    // Unsubscribe from progressCallback1.
    downloadTask.off('progress', progressCallback1);
    // Unsubscribe from all callbacks of download progress events.
    downloadTask.off('progress');
  }).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)}`);
}

on('complete'|'pause'|'remove')7+

on(type: 'complete'|'pause'|'remove', callback: () => void): void

Subscribes to download events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
- 'complete': download task completion.
- 'pause': download task pause.
- 'remove': download task removal.
callback function Yes Callback used to return the result.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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);
  }).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)}`);
}

off('complete'|'pause'|'remove')7+

off(type: 'complete'|'pause'|'remove', callback?: () => void): void

Unsubscribes from download events.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'complete': download task completion.
- 'pause': download task pause.
- 'remove': download task removal.
callback function No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let completeCallback1 = () => {
      console.info('Download delete complete notification.');
    };
    let completeCallback2 = () => {
      console.info('Download delete complete notification.');
    };
    downloadTask.on('complete', completeCallback1);
    downloadTask.on('complete', completeCallback2);
    // Unsubscribe from completeCallback1.
    downloadTask.off('complete', completeCallback1);
    // Unsubscribe from all callbacks of the download completion events.
    downloadTask.off('complete');

    let pauseCallback1 = () => {
      console.info('Download delete pause notification.');
    };
    let pauseCallback2 = () => {
      console.info('Download delete pause notification.');
    };
    downloadTask.on('pause', pauseCallback1);
    downloadTask.on('pause', pauseCallback2);
    // Unsubscribe from pauseCallback1.
    downloadTask.off('pause', pauseCallback1);
    // Unsubscribe from all callbacks of the download pause events.
    downloadTask.off('pause');

    let removeCallback1 = () => {
      console.info('Download delete remove notification.');
    };
    let removeCallback2 = () => {
      console.info('Download delete remove notification.');
    };
    downloadTask.on('remove', removeCallback1);
    downloadTask.on('remove', removeCallback2);
    // Unsubscribe from removeCallback1.
    downloadTask.off('remove', removeCallback1);
    // Unsubscribe from all callbacks of the download removal events.
    downloadTask.off('remove');
  }).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)}`);
}  

on('fail')7+

on(type: 'fail', callback: (err: number) => void): void

Subscribes to download failure events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to subscribe to.
- 'fail': download task failure.
callback function Yes Callback for the download task failure event.

Parameters of the callback function

Name Type Mandatory Description
err number Yes Error code of the download failure. For details about the error codes, see Download Error Codes.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let failCallback = (err: number) => {
      console.error(`Failed to download the task. Code: ${err}`);
    };
    downloadTask.on('fail', failCallback);
  }).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)}`);
}

off('fail')7+

off(type: 'fail', callback?: (err: number) => void): void

Unsubscribes from download failure events.

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
type string Yes Type of the event to unsubscribe from.
- 'fail': download task failure.
callback function No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Parameters of the callback function

Name Type Mandatory Description
err number Yes Error code of the download failure. For details about the error codes, see Download Error Codes.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 The parameters check fails. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    let failCallback1 = (err: number) => {
      console.error(`Failed to download the task. Code: ${err}`);
    };
    let failCallback2 = (err: number) => {
      console.error(`Failed to download the task. Code: ${err}`);
    };
    downloadTask.on('fail', failCallback1);
    downloadTask.on('fail', failCallback2);
    // Unsubscribe from failCallback1.
    downloadTask.off('fail', failCallback1);
    // Unsubscribe from all callbacks of the download failure events.
    downloadTask.off('fail');
  }).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)}`);
}

delete9+

delete(): Promise<boolean>

Deletes this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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}`);
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

delete9+

delete(callback: AsyncCallback<boolean>): void

Deletes this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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.');
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

getTaskInfo9+

getTaskInfo(): Promise<DownloadInfo>

Obtains the information about this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<DownloadInfo> Promise used to return a DownloadInfo object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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}`)
    });
  }).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)}`);
} 

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

getTaskInfo9+

getTaskInfo(callback: AsyncCallback<DownloadInfo>): void

Obtains the information about this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<DownloadInfo> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the DownloadInfo object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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');
      }
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

getTaskMimeType9+

getTaskMimeType(): Promise<string>

Obtains the MIME type (that is, media type of resources in HTTP) of a download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<string> Promise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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}`)
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

getTaskMimeType9+

getTaskMimeType(callback: AsyncCallback<string>): void

Obtains the MIME type (that is, media type of resources in HTTP) of a download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<string> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the MimeType object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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');
      }
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

suspend9+

suspend(): Promise<boolean>

Suspends this download task. You can use restore to restore the download. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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}`);
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

suspend9+

suspend(callback: AsyncCallback<boolean>): void

Suspends this download task. You can use restore to restore the download. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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.');
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

restore9+

restore(): Promise<boolean>

Restores this download task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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}`);
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

restore9+

restore(callback: AsyncCallback<boolean>): void

Restores this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
try {
  // Replace the URL with the HTTP address of the real server.
  request.downloadFile(context, { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => {
    let downloadTask: request.DownloadTask = data;
    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.');
    });
  }).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)}`);
}

NOTE

The scenarios for triggering error code 401 the parameters check fails do not exist. Therefore, this error code is removed from API version 12.

remove(deprecated)

remove(): Promise<boolean>

Removes this download task. This API uses a promise to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<boolean> Promise used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

Removes this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is deprecated since API version 9. You are advised to use delete9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<boolean> Yes Callback used to return the result. The value true indicates that the operation is successful; false indicates the opposite.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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>

Queries this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getTaskInfo9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<DownloadInfo> Promise used to return the DownloadInfo object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

Queries this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getTaskInfo9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<DownloadInfo> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the DownloadInfo object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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>

Queries the MIME type of this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getTaskMimeType9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<string> Promise used to return the result.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

Queries the MIME type of this download task. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getTaskMimeType9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<string> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the MimeType object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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>

Pauses this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use suspend9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use suspend9+ instead.

Pauses this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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>

Resumes this download task. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use restore9+ instead.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use restore9+ instead.

Resumes this download task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.MiscServices.Download

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 The permissions check fails.

Example

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

Defines the download task configuration.

System capability: SystemCapability.MiscServices.Download

Name Type Mandatory Description
url string Yes Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; since API version 15, the value contains a maximum of 8192 characters. Intercepting HTTP is supported.
header Object No HTTPS flag header to be included in the download request.
enableMetered boolean No Whether download is allowed on a metered connection. The value true means the download is allowed, and false means the opposite. The default value is false.
Note: In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.
enableRoaming boolean No Whether download is allowed on a roaming network. The value true means the download is allowed, and false means the opposite. The default value is false.
description string No Description of the download session. The default value is an empty string.
filePath7+ string No Path where the downloaded file is stored. The default value is the cache directory of the caller (that is, the input context). The default file name is the part truncated from the last slash (/) in the URL.
- In the FA model, use context to obtain the application storage path.
- In the stage model, use AbilityContext to obtain the application storage path.
networkType number No Network type allowed for download. The default value can be NETWORK_MOBILE or NETWORK_WIFI.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000
title string No Download task name.
background9+ boolean No Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel. The value true means the parameter is enabled, and false means the opposite. The default value is false.

DownloadInfo7+

Defines the download task information, which is the callback parameter of the getTaskInfo9+ API.

System capability: SystemCapability.MiscServices.Download

Name Type Mandatory Description
downloadId number Yes Download task ID.
failedReason number Yes Cause of the download failure. The value can be any constant in Download Error Codes.
fileName string Yes Name of the downloaded file.
filePath string Yes URI of the saved file.
pausedReason number Yes Cause of download pause. The value can be any constant in Causes of Download Pause.
status number Yes Download task status code. The value can be any constant in Download Task Status Codes.
targetURI string Yes URI of the downloaded file.
downloadTitle string Yes Name of the download task.
downloadTotalBytes number Yes Total size of the files to download, in bytes.
description string Yes Description of the download task.
downloadedBytes number Yes Real-time download size, in bytes.

Action10+

Defines action options.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
DOWNLOAD 0 Download.
UPLOAD 1 Upload.

Mode10+

Defines mode options.
After foreground tasks of an application are switched to the background for a period of time, background tasks are not affected but foreground tasks will fail or pause.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
BACKGROUND 0 Background task.
FOREGROUND 1 Foreground task.

Network10+

Defines network options.
If the network does not meet the preset conditions, the tasks that have not been executed will await for execution, and the tasks that are being executed will fail or pause.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
ANY 0 Network of any type.
WIFI 1 Wi-Fi network.
CELLULAR 2 Cellular data network.

BroadcastEvent11+

Defines a custom system event. You can use a common event API to obtain the event. The upload and download SA has the ohos.permission.SEND_TASK_COMPLETE_EVENT permission. You can configure the level-2 configuration file to which the metadata of an event points to intercept other event senders.

Use the CommonEventData type to transmit data related to common events. The members in CommonEventData are different from those described in CommonEventData. Specifically, CommonEventData.code indicates the task status, which is 0x40 COMPLETE or 0x41 FAILED, and CommonEventData.data indicates the task ID.

For details about how to obtain the event configuration and configure the level-2 configuration file, see Subscribing to Common Events in Static Mode (for System Applications Only).

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
COMPLETE 'ohos.request.event.COMPLETE' Task completion event. The returned event code can be 0x40 or 0x41, depending on whether the task is successful or fails.

FileSpec10+

Provides the file information of a table item.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
path string Yes File path.
- Relative path, which is in the cache directory of the caller.
Example: ./xxx/yyy/zzz.html or xxx/yyy/zzz.html
- Internal protocol path, which can be internal:// or its subdirectory. internal indicates the cache directory of the caller (that is, the input context), and internal://cache corresponds to context.cacheDir.
Example: internal://cache/path/to/file.txt
- Application sandbox directory. Only the base directory and its subdirectories are supported.
Example: /data/storage/el1/base/path/to/file.txt
- File protocol path, which must match the application bundle name. Only the base directory and its subdirectories are supported.
Example: file://com.example.test/data/storage/el2/base/file.txt
- Public files of users. Only upload tasks and foreground tasks are supported
Example: file://media/Photo/path/to/file.img
Atomic service API: This API can be used in atomic services since API version 11.
mimeType(deprecated) string No MIME type of the file, which is obtained from the file name. The default value is the file name extension.
Atomic service API: This API can be used in atomic services since API version 11.
This API is deprecated since API version 18. You are advised to use contentType instead.
contentType18+ string No Content type of the file. The default value is the file name extension. This option is filled in the Content-Type field specified in the HTTP form.
filename string No File name. The default value is obtained from the file path.
Atomic service API: This API can be used in atomic services since API version 11.
extras object No Additional information. This parameter is not included in HTTP requests.
Atomic service API: This API can be used in atomic services since API version 11.

FormItem10+

Describes the form item of a task.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
name string Yes Form parameter name.
value string | FileSpec | Array<FileSpec> Yes Form parameter value.

Config10+

Provides the configuration information of an upload or download task.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
action Action Yes Task action.
- UPLOAD: Upload tasks.
- DOWNLOAD: Download tasks.
Atomic service API: This API can be used in atomic services since API version 11.
url string Yes Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; since API version 15, the value contains a maximum of 8192 characters. Intercepting HTTP is supported.
Atomic service API: This API can be used in atomic services since API version 11.
title string No Task title. The value contains a maximum of 256 characters. The default value is upload or download in lowercase. Set the value to that of action.
Atomic service API: This API can be used in atomic services since API version 11.
description string No Task description. The value contains a maximum of 1024 characters. The default value is a null string.
Atomic service API: This API can be used in atomic services since API version 11.
mode Mode No Task mode. The default mode is background. Since API version 20, the task mode for downloading files to the user file folder must be set to request.agent.Mode.FOREGROUND.
Atomic service API: This API can be used in atomic services since API version 11.
overwrite boolean No Whether to overwrite an existing file during the download. The default value is false.
- true: Overwrite the existing file.
- false: Do not overwrite the existing file. In this case, the download fails.
Since API version 20, the overwrite mode for downloading files to the user file folder must be set to true.
Atomic service API: This API can be used in atomic services since API version 11.
method string No Standard HTTP method for the task. The value can be GET, POST, or PUT, which is case-insensitive.
- For the upload task, use PUT or POST. The default value is PUT.
- For the download task, use GET or POST. The default value is GET.
Atomic service API: This API can be used in atomic services since API version 11.
headers object No HTTP headers to be included in the task.
- For the upload task, the default Content-Type is multipart/form-data.
- For the download task, the default Content-Type is application/json.
Atomic service API: This API can be used in atomic services since API version 11.
data string | Array<FormItem> No - For the download task, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- For the upload task, the value is Array<FormItem>. Since API version 15, a maximum of 100 files can be uploaded in a single task. This parameter is left empty by default.
Atomic service API: This API can be used in atomic services since API version 11.
saveas string No Path for storing downloaded files. The options are as follows:
- Relative path, which is in the cache directory of the caller, for example, ./xxx/yyy/zzz.html or xxx/yyy/zzz.html.
- Internal protocol path, which can be internal:// or its subdirectory. internal indicates the cache directory of the caller (that is, the input context), and internal://cache corresponds to context.cacheDir, for example, internal://cache/path/to/file.txt.
- Application sandbox path. Only the base directory and its subdirectories are supported, for example, /data/storage/el1/base/path/to/file.txt.
- File protocol path, which can be the path of an application file or a user file. For the application file, the application bundle name must be matched and only the base directory and its subdirectories are supported, for example, file://com.example.test/data/storage/el2/base/file.txt. For the user file, its path must be the user file URI created by the caller.
Since API version 20, the default file path can be the cache path of the caller (that is, the passed context), except for downloading network resource files to the user file. The default file name is the part truncated from the last slash (/) in the URL.
Atomic service API: This API can be used in atomic services since API version 11.
network Network No Network used for the task. The default value is ANY (Wi-Fi or cellular).
Atomic service API: This API can be used in atomic services since API version 11.
metered boolean No Whether the task is allowed on a metered connection.
- true: The task is allowed on a metered connection.
- false (default): The task is not allowed on a metered connection.
Atomic service API: This API can be used in atomic services since API version 11.
roaming boolean No Whether the task is allowed on a roaming network.
- true (default): The task is allowed on a roaming connection.
- false: The task is not allowed on a roaming connection.
Atomic service API: This API can be used in atomic services since API version 11.
retry boolean No Whether automatic retry is enabled for the task. This parameter is only applicable to background tasks.
- true (default): The automatic retry is enabled.
- false: The automatic retry is disabled.
Atomic service API: This API can be used in atomic services since API version 11.
redirect boolean No Whether redirection is allowed.
- true (default): The redirection is allowed.
- false: The redirection is not allowed.
Atomic service API: This API can be used in atomic services since API version 11.
proxy12+ string No Proxy address. The value contains a maximum of 512 characters.
It is in the format of http://<domain or address>:<port>. By default, this parameter is left blank.
index number No Path index of the task. It is usually used for resumable transfers. The default value is 0.
Atomic service API: This API can be used in atomic services since API version 11.
begins number No File start point of the task. It is usually used for resumable transfers. The default value is 0. The value is a closed interval.
- For the download task, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.
- For the upload task, the value is obtained at the beginning of the upload.
Atomic service API: This API can be used in atomic services since API version 11.
ends number No File end point of the task. It is usually used for resumable transfers. The default value is -1. The value is a closed interval.
- For the download task, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.
- For the upload task, the value is obtained at the end of the upload.
Atomic service API: This API can be used in atomic services since API version 11.
gauge boolean No Whether to send progress notifications. This parameter applies only to background tasks. The default value is false.
- false: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.
- true: Progress notifications are sent to indicate the result of each file.
Atomic service API: This API can be used in atomic services since API version 11.
precise boolean No - If this parameter is set to true, the task fails when the file size cannot be obtained.
- If this parameter is set to false, the task continues when the file size is set to -1.
The default value is false.
Atomic service API: This API can be used in atomic services since API version 11.
token string No Task token. To query a task with a token, you need to provide the token and use request.agent.touch. Otherwise, the specified task cannot be queried. The value contains 8 to 2048 bytes. This parameter is left empty by default.
Atomic service API: This API can be used in atomic services since API version 11.
priority11+ number No Priority of the task. The priority of a foreground task is higher than that of a background task. For tasks in the same mode, a smaller value indicates a higher priority.
Default value: 0
extras object No Additional information of the task. This parameter is left empty by default.
Atomic service API: This API can be used in atomic services since API version 11.
multipart15+ boolean No Whether to use a single request to upload multiple files. If yes, multipart/form-data must be used.
- false: A single request is used to upload one file.
- true: A single request is used to upload multiple files.
The default value is false.
notification15+ Notification No Custom settings for the notification bar. The default value is {}.
minSpeed20+ MinSpeed No Minimum speed, which is disabled by default.
timeout20+ Timeout No Custom timeout interval. The default connection timeout interval is 60 seconds, and the default total timeout interval is 604800 seconds (one week).

State10+

Defines the current task status.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
INITIALIZED 0x00 The task is initialized based on the configuration specified in Config.
WAITING 0x10 The task lacks resources for running or the resources for retries, or does not match the network status.
RUNNING 0x20 The task is being executed.
RETRYING 0x21 The task has failed at least once and is being executed again.
PAUSED 0x30 The task is suspended and will be resumed later.
STOPPED 0x31 The task is stopped.
COMPLETED 0x40 The task is complete.
FAILED 0x41 The task fails.
REMOVED 0x50 The task is removed.

Progress10+

Describes the data structure of the task progress.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
state State Yes Current task status.
index number Yes Index of the file that is being processed in the task.
processed number Yes Size of processed data in the current file in the task, in bytes.
sizes Array<number> Yes Size of a file in a task, in bytes. If the server uses the chunk mode for data transmission and the total file size cannot be obtained from the request header, the value of sizes is treated as -1.
extras object No Extra information of the task, for example, the header and body of the response from the server.

Faults10+

Defines the cause of a task failure.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
OTHERS 0xFF Other fault.
Atomic service API: This API can be used in atomic services since API version 11.
DISCONNECTED 0x00 Network disconnection.
Atomic service API: This API can be used in atomic services since API version 11.
TIMEOUT 0x10 Timeout.
Atomic service API: This API can be used in atomic services since API version 11.
PROTOCOL 0x20 Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416).
Atomic service API: This API can be used in atomic services since API version 11.
PARAM12+ 0x30 Parameter error, for example, incorrect URL format.
Atomic service API: This API can be used in atomic services since API version 12.
FSIO 0x40 File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation.
Atomic service API: This API can be used in atomic services since API version 11.
DNS12+ 0x50 DNS resolution error.
Atomic service API: This API can be used in atomic services since API version 12.
TCP12+ 0x60 TCP connection error.
Atomic service API: This API can be used in atomic services since API version 12.
SSL12+ 0x70 SSL connection error, for example, a certificate error or certificate verification failure.
Atomic service API: This API can be used in atomic services since API version 12.
REDIRECT12+ 0x80 Redirection error.
Atomic service API: This API can be used in atomic services since API version 12.
LOW_SPEED20+ 0x90 Low speed.

NOTE

In API version 12 or earlier, only serial connection to the IP addresses associated with the specified domain name is supported, and the connection time for a single IP address is not controllable. If the first IP address returned by the DNS is blocked, a handshake timeout may occur, leading to a TIMEOUT error.

Filter10+

Defines the filter criteria.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
before number No Unix timestamp of the end time, in milliseconds. The default value is the invoking time.
after number No Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours.
state State No Task state. If this parameter is not set, all tasks are queried.
action Action No Task action.
- UPLOAD: Upload tasks.
- DOWNLOAD: Download tasks.
- If this parameter is not set, all tasks are queried.
mode Mode No Task mode.
- FOREGROUND: foreground task.
- BACKGROUND: background task.
- If this parameter is not set, all tasks are queried.

TaskInfo10+

Defines the data structure of the task information for query. The fields available vary depending on the query type.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
saveas string No Path for storing downloaded files.
url string No Task URL.
It can be obtained through request.agent.show10+ or request.agent.touch10+.
data string | Array<FormItem> No Task value.
It can be obtained through request.agent.show10+ or request.agent.touch10+.
tid string Yes Task ID.
title string Yes Task title.
description string Yes Task description.
action Action Yes Task action.
- UPLOAD: Upload tasks.
- DOWNLOAD: Download tasks.
mode Mode Yes Task mode.
- FOREGROUND: foreground task.
- BACKGROUND: background task.
priority11+ number Yes Task priority. The priority of a foreground task is higher than that of a background task. For tasks in the same mode, a smaller value indicates a higher priority.
mimeType string Yes MIME type in the task configuration.
progress Progress Yes Task progress.
gauge boolean Yes Whether to send progress notifications. This parameter applies only to background tasks.
- false: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.
- true: Progress notifications are sent to indicate the result of each file.
ctime number Yes Unix timestamp when the task is created, in milliseconds. The value is generated by the system of the current device.
NOTE
When request.agent.search10+ is used for query, this value must be within the range of [after,before] for the task ID to be obtained. For details about before and after, see Filter.
mtime number Yes Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device.
retry boolean Yes Whether automatic retry is enabled for the task. This parameter applies only to background tasks.
- true: The automatic retry is enabled.
- false: The automatic retry is disabled.
tries number Yes Number of retries of the task.
faults Faults Yes Failure cause of the task.
reason string Yes Reason why the task is waiting, failed, stopped, or paused.
extras object No Extra information of the task.

HttpResponse12+

Describes the data structure of the task response header.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
version string Yes HTTP version.
statusCode number Yes HTTP response status code.
reason string Yes HTTP response cause.
headers Map<string, Array<string>> Yes HTTP response header.

Notification15+

Describes the custom information of the notification bar.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
title string No Custom title, with a maximum of 1024 bytes. The default title is used if this parameter is not set.
text string No Custom body text, with a maximum of 3072 bytes. The default text is used if this parameter is not set.

GroupConfig15+

Describes group configuration options for download tasks.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
gauge boolean No Whether to send progress notifications. This parameter applies only to background tasks.
- true: The progress, success, and failure notifications are displayed.
- false: Only success and failure notifications are displayed.
The default value is false.
notification15+ Notification Yes Custom settings for the notification bar. The default value is {}.

WaitingReason20+

Enumerates the reasons why a task is waiting.

System capability: SystemCapability.Request.FileTransferAgent

Name Value Description
TASK_QUEUE_FULL 0x00 The task queue is full.
NETWORK_NOT_MATCH 0x01 The required network conditions are not met.
APP_BACKGROUND 0x02 The application has been running in the background for a long time.
USER_INACTIVATED 0x03 The user is inactive.

MinSpeed20+

Defines the minimum speed of a task. If the task speed is lower than the preset value for a specified period of time, the task fails. The failure cause is LOW_SPEED.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Read-Only Optional Description
speed number No No Minimum speed of a task, in byte/s. If the task speed is lower than this value for a specified period of time, the task fails. If the value is set to 0, there is no minimum speed limit.
duration number No No Duration during which the task speed can be lower than the minimum speed, in seconds. If the task speed is lower than the preset value for a specified period of time, the task fails. If the value is set to 0, there is no minimum speed limit.

Timeout20+

Defines the timeout configuration of a task.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Read-Only Optional Description
connectionTimeout number No Yes Task connection timeout interval, in seconds. The connection timeout interval indicates the maximum time required for establishing a connection between the client and server. If this parameter is not set, the default value 60 is used. The minimum value is 1.
totalTimeout number No Yes Total timeout interval of a task, in seconds. The total timeout interval includes the time required for establishing a connection, sending a request, and receiving a response. If this parameter is not set, the default value 604800 is used. The minimum value is 1, and the maximum value is 604800 (that is, one week).

Task10+

Implements an upload or download task. Before using this API, you must obtain a Task object, from a promise through request.agent.create10+ or from a callback through request.agent.create10+.

Attributes

Task attributes include the task ID and task configuration.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Name Type Mandatory Description
tid string Yes Task ID, which is unique and automatically generated by the system.
config Config Yes Task configuration.

NOTE

The Task object and its mounting callback function are released and automatically reclaimed by the system after the remove method is called.

on('progress')10+

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

Subscribes to task progress changes. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'progress': task progress.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.on('progress', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('completed')10+

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

Subscribes to task completion events. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'completed': task completion.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.on('completed', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('failed')10+

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

Subscribes to task failure events. This API uses an asynchronous callback to return the result. You can call request.agent.show10+ to check the error.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'fail': task failure.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.on('failed', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('pause')11+

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

Subscribes to task pause events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'pause': task pause.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 pause.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('pause', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.pause();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('resume')11+

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

Subscribes to task resume events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'resume': task resume.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 resume.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('resume', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.pause();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.resume();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('remove')11+

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

Subscribes to task removal events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'remove': task removal.
callback function Yes Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 remove.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('remove', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  request.agent.remove(task.tid);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('response')12+

on(event: 'response', callback: Callback<HttpResponse>): void

Subscribes to task response headers. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'response': task response.
callback Callback<HttpResponse> Yes Callback used to return the data structure of the task response header.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOnTest",
  value: {
    filename: "taskOnTest.avi",
    path: "./taskOnTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 = (response: request.agent.HttpResponse) => {
  console.info('upload task response.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('response', createOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('faultOccur')20+

on(event: 'faultOccur', callback: Callback<Faults>): void

Subscribes to task failure events. This API uses a callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'faultOccur': task failure.
callback Callback<Faults> Yes Callback used to return the failure cause of the task.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
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', // Replace the URL with the HTTP address of the real server.
  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 faultOnCallback = (faults: request.agent.Faults) => {
  console.info('upload task failed.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('faultOccur', faultOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

on('wait')20+

on(event: 'wait', callback: Callback<WaitingReason>): void

Subscribes to task wait events. This API uses a callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'wait': The task is waiting.
callback Callback<WaitingReason> Yes Callback used to return the waiting reason of the task.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
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', // Replace the URL with the HTTP address of the real server.
  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 waitOnCallback = (reason: request.agent.WaitingReason) => {
  console.info('upload task waiting.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('wait', waitOnCallback);
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('progress')10+

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

Unsubscribes from task progress events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'progress': task progress.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task progress.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task progress.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('progress', createOffCallback1);
  task.on('progress', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('progress', createOffCallback1);
  // Unsubscribe from all callbacks of task progress changes.
  task.off('progress');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('completed')10+

off(event: 'completed', callback?: (progress: Progress) => void): void

Unsubscribes from task completion events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'completed': task completion.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task completed.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task completed.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('completed', createOffCallback1);
  task.on('completed', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('completed', createOffCallback1);
  // Unsubscribe from all callbacks of the task completion events.
  task.off('completed');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('failed')10+

off(event: 'failed', callback?: (progress: Progress) => void): void

Unsubscribes from task failure events.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'failed': task failure.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task failed.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task failed.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('failed', createOffCallback1);
  task.on('failed', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('failed', createOffCallback1);
  // Unsubscribe from all callbacks of the task failure events.
  task.off('failed');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('pause')11+

off(event: 'pause', callback?: (progress: Progress) => void): void

Unsubscribes from the foreground task pause event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'pause': task pause.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task pause.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task pause.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('pause', createOffCallback1);
  task.on('pause', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('pause', createOffCallback1);
  // Unsubscribe from all callbacks of the foreground task pause event.
  task.off('pause');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('resume')11+

off(event: 'resume', callback?: (progress: Progress) => void): void

Unsubscribes from the foreground task resume event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'resume': task resume.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task resume.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task resume.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('resume', createOffCallback1);
  task.on('resume', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('resume', createOffCallback1);
  // Unsubscribe from all callbacks of the foreground task resume event.
  task.off('resume');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('remove')11+

off(event: 'remove', callback?: (progress: Progress) => void): void

Unsubscribes from the task removal event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- 'remove': task removal.
callback function No Callback used to return the data structure of the task progress.

Parameters of the callback function

Name Type Mandatory Description
progress Progress Yes Task progress.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.Progress) => {
  console.info('upload task remove.');
};
let createOffCallback2 = (progress: request.agent.Progress) => {
  console.info('upload task remove.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('remove', createOffCallback1);
  task.on('remove', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('remove', createOffCallback1);
  // Unsubscribe from all callbacks of the task removal event.
  task.off('remove');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('response')12+

off(event: 'response', callback?: Callback<HttpResponse>): void

Unsubscribes from task response headers.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to unsubscribe from.
- response: task response.
callback Callback<HttpResponse> No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Error codes

For details about the error codes, see Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "taskOffTest",
  value: {
    filename: "taskOffTest.avi",
    path: "./taskOffTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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 createOffCallback1 = (progress: request.agent.HttpResponse) => {
  console.info('upload task response.');
};
let createOffCallback2 = (progress: request.agent.HttpResponse) => {
  console.info('upload task response.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('response', createOffCallback1);
  task.on('response', createOffCallback2);
  // Unsubscribe from createOffCallback1.
  task.off('response', createOffCallback1);
  // Unsubscribe from all callbacks of the task response event.
  task.off('response');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('faultOccur')20+

off(event: 'faultOccur', callback?: Callback<Faults>): void

Unsubscribes from the task failure event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'faultOccur': task failure.
callback Callback<Faults> No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
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', // Replace the URL with the HTTP address of the real server.
  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 faultOffCallback1 = (faults: request.agent.Faults) => {
  console.info('upload task failed.');
};
let faultOffCallback2 = (faults: request.agent.Faults) => {
  console.info('upload task failed.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('faultOccur', faultOffCallback1);
  task.on('faultOccur', faultOffCallback2);
  // Unsubscribe from faultOffCallback1.
  task.off('faultOccur', faultOffCallback1);
  // Unsubscribe from all callbacks of the task failure event.
  task.off('faultOccur');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

off('wait')20+

off(event: 'wait', callback?: Callback<WaitingReason>): void

Unsubscribes from the task wait event.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
event string Yes Type of the event to subscribe to.
- 'wait': The task is waiting.
callback Callback<WaitingReason> No Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
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', // Replace the URL with the HTTP address of the real server.
  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 waitOffCallback1 = (reason: request.agent.WaitingReason) => {
  console.info('upload task waiting.');
};
let waitOffCallback2 = (reason: request.agent.WaitingReason) => {
  console.info('upload task waiting.');
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  task.on('wait', waitOffCallback1);
  task.on('wait', waitOffCallback2);
  // Unsubscribe from waitOffCallback1.
  task.off('wait', waitOffCallback1);
  // Unsubscribe from all callbacks of the task wait event.
  task.off('wait');
  console.info(`Succeeded in creating a upload task. result: ${task.tid}`);
  task.start();
}).catch((err: BusinessError) => {
  console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

start10+

start(callback: AsyncCallback<void>): void

Starts a task. This API uses an asynchronous callback to return the result.
Tasks in the following states can be started:

  1. Task created by request.agent.create.
  2. Download tasks that are created by request.agent.create but have failed or paused.

Required permissions: ohos.permission.INTERNET

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, 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}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

start10+

start(): Promise<void>

Starts a task. This API uses a promise to return the result.
Tasks in the following states can be started:

  1. Task created by request.agent.create.
  2. Download tasks that are created by request.agent.create but have failed or paused.

Required permissions: ohos.permission.INTERNET

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, 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}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

pause10+

pause(callback: AsyncCallback<void>): void

Pauses a task that is waiting, running, or retrying. A paused task can be resumed by resume. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

ID Error Message
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  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>

Pauses a task that is waiting, running, or retrying. A paused task can be resumed by resume. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

ID Error Message
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.pause().then(() => {
    console.info(`Succeeded in pausing a download task. `);
  }).catch((err: BusinessError) => {
    console.error(`Failed to pause 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}`);
});

resume10+

resume(callback: AsyncCallback<void>): void

Resumes a paused task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.pause();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  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>

Resumes a paused task. This API uses a promise to return the result.

Required permissions: ohos.permission.INTERNET

System capability: SystemCapability.Request.FileTransferAgent

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  task.pause();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  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

Stops a task that is running, waiting, or retrying. A paused task can be resumed by start. This API uses an asynchronous callback to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes.

ID Error Message
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  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>

Stops a task that is running, waiting, or retrying. A paused task can be resumed by start. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes.

ID Error Message
13400003 Task service ability error.
21900007 Operation with wrong task state.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then((task: request.agent.Task) => {
  task.start();
  for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation.
  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}`);
});

setMaxSpeed18+

setMaxSpeed(speed: number): Promise<void>

Sets the maximum number of bytes that can be transmitted by a task per second. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
speed number Yes Maximum number of bytes that can be transmitted by a task per second, with a minimum of 16384 bytes. The value cannot be less than the minimum speed value specified by MinSpeed.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let config: request.agent.Config = {
  action: request.agent.Action.DOWNLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  saveas: "./",
};
request.agent.create(context, config).then((task: request.agent.Task) => {
  // Set the maximum transmission speed.
  task.setMaxSpeed(10 * 1024 * 1024).then(() => {
    console.info(`Succeeded in setting the max speed of the task. result: ${task.tid}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to set the max speed of the 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

Creates an upload or download task and adds it to the queue. This API uses an asynchronous callback to return the result. HTTP/HTTPS is supported.

Required permissions: ohos.permission.INTERNET

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
config Config Yes Task configuration.
context BaseContext Yes Application-based context.
callback AsyncCallback<Task> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the Task object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400001 Invalid file or file system error.
13400003 Task service ability error.
21900004 The application task queue is full.
21900005 Operation with wrong task mode.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "createTest",
  value: {
    filename: "createTest.avi",
    path: "./createTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config, async (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}`);
  await task.start();
  // You need to manually call remove() to end the lifecycle of the task object.
  request.agent.remove(task.tid);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.agent.create10+

create(context: BaseContext, config: Config): Promise<Task>

Creates an upload or download task and adds it to the queue. This API uses a promise to return the result. HTTP/HTTPS is supported.

Required permissions: ohos.permission.INTERNET

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
config Config Yes Task configuration.

Return value

Type Description
Promise<Task> Promise used to return the configuration about the created task.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
201 Permission denied.
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400001 Invalid file or file system error.
13400003 Task service ability error.
21900004 The application task queue is full.
21900005 Operation with wrong task mode.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let attachments: Array<request.agent.FormItem> = [{
  name: "createTest",
  value: {
    filename: "createTest.avi",
    path: "./createTest.avi",
  }
}];
let config: request.agent.Config = {
  action: request.agent.Action.UPLOAD,
  url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server.
  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(context, config).then(async (task: request.agent.Task) => {
  console.info(`Succeeded in creating a download task. result: ${task.config}`);
  await task.start();
  // You need to manually call remove() to end the lifecycle of the task object.
  request.agent.remove(task.tid);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
});

NOTE

For details about how to obtain the context in the example, see Obtaining the Context of UIAbility.

request.agent.getTask11+

getTask(context: BaseContext, id: string, token?: string): Promise<Task>

Obtains task information based on the task ID. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
context BaseContext Yes Application-based context.
id string Yes Task ID.
token string No Token for task query.

Return value

Type Description
Promise<Task> Promise used to return the configuration about the obtained task.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
request.agent.getTask(context, "123456").then((task: request.agent.Task) => {
  console.info(`Succeeded in querying a task. result: ${task.tid}`);
}).catch((err: BusinessError) => {
  console.error(`Failed to query a task, Code: ${err.code}, message: ${err.message}`);
});

request.agent.remove10+

remove(id: string, callback: AsyncCallback<void>): void

Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result. After this API is called, the task object and its callback function are released.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.
callback AsyncCallback<void> Yes Callback used to return the result. If the operation is successful, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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

request.agent.remove10+

remove(id: string): Promise<void>

Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result. After this API is called, the task object and its callback function are released.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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

Queries a task details based on the task ID. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.
callback AsyncCallback<TaskInfo> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the TaskInfo object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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>

Queries a task details based on the task ID. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.

Return value

Type Description
Promise<TaskInfo> Promise used to return the TaskInfo object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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

Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.
token string Yes Token for task query.
callback AsyncCallback<TaskInfo> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the TaskInfo object obtained. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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>

Queries the task details based on the task ID and token. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
id string Yes Task ID.
token string Yes Token for task query.

Return value

Type Description
Promise<TaskInfo> Promise used to return the TaskInfo object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.
21900006 Task removed or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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

Searches for task IDs based on Filter. The IDs of all tasks from the invoking time to 24 hours ago are searched. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
callback AsyncCallback<Array<string>> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the task ID. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

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

Searches for task IDs based on Filter. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
filter Filter Yes Filter criteria.
callback AsyncCallback<Array<string>> Yes Callback used to return the result. If the operation is successful, err is undefined and data is the task ID. Otherwise, err is an error object.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let filter: request.agent.Filter = {
  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>>

Searches for task IDs based on Filter. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
filter Filter No Filter criteria.

Return value

Type Description
Promise<Array<string>> Promise used to return the task IDs that meet the filter criteria.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

let filter: request.agent.Filter = {
  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.createGroup15+

createGroup(config: GroupConfig): Promise<string>

Creates a group based on GroupConfig15+ and returns the group ID. This API uses a promise to return the result.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
config GroupConfig15+ Yes Group options for a download task.

Return value

Type Description
Promise<string> Promise used to return the result.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Prepare the GroupConfig object.
let config: request.agent.GroupConfig = {
    notification: {},
};
// Call the createGroup API to create a group.
request.agent.createGroup(config).then((gid: string) => {
  console.info(`Succeeded in creating a download task group. `);
}).catch((err: BusinessError) => {
  console.error(`Failed to create a download group, Code: ${err.code}, message: ${err.message}`);
});

request.agent.attachGroup15+

attachGroup(gid: string, tids: string[]): Promise<void>

Attaches multiple download task IDs to a specified group ID. This API uses a promise to return the result.

If any task ID does not meet the attachment conditions, all tasks in the list will not be added to the group.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
gid string Yes Target group ID.
tids string[] Yes List of task IDs to attach.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.
21900005 Operation with wrong task mode.
21900006 Task removed or not found.
21900007 Operation with wrong task state.
21900008 Group deleted or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Prepare the group ID and task ID list.
let groupId: string = "123456789";
let taskIds: string[] = ["1111", "2222", "3333", "4444"];
// Call the attachGroup API to add a task ID list to the group.
request.agent.attachGroup(groupId, taskIds).then(() => {
  console.info(`Succeeded in attaching tasks to the download task group.`);
}).catch((err: BusinessError) => {
  console.error(`Failed to attach tasks to the download group, Code: ${err.code}, message: ${err.message}`);
});

request.agent.deleteGroup15+

deleteGroup(gid: string): Promise<void>

Deletes a specified group. No task ID can be added to the group. This API uses a promise to return the result.

When all tasks in a group are succeeded, failed, or removed and the group is deleted , the completion and failure notifications of this group are displayed.

System capability: SystemCapability.Request.FileTransferAgent

Parameters

Name Type Mandatory Description
gid string Yes Target group ID.

Return value

Type Description
Promise<void> Promise that returns no value.

Error codes

For details about the error codes, see Upload and Download Error Codes and Universal Error Codes.

ID Error Message
401 Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.
13400003 Task service ability error.
21900008 Group deleted or not found.

Example

import { BusinessError } from '@kit.BasicServicesKit';

// Prepare the group ID.
let groupId: string = "123456789";

// Call the deleteGroup API to delete a group.
request.agent.deleteGroup(groupId).then(() => {
  console.info(`Succeeded in deleting the download task group.`);
}).catch((err: BusinessError) => {
  console.error(`Failed to delete the download group, Code: ${err.code}, message: ${err.message}`);
});
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
其他
1
https://gitee.com/openharmony/docs.git
git@gitee.com:openharmony/docs.git
openharmony
docs
docs
master

搜索帮助