1# @ohos.request (Upload and Download) 2 3The **request** module provides applications with basic upload, download, and background transmission agent capabilities. 4 5> **NOTE** 6> 7> 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. 8 9 10## Modules to Import 11 12 13```js 14import { request } from '@kit.BasicServicesKit'; 15``` 16 17## Constants 18 19**System capability**: SystemCapability.MiscServices.Download 20 21> **NOTE** 22> 23> **Network type**: set **networkType** in [DownloadConfig](#downloadconfig) to specify the network type for the download service.<br> 24> 25> **Download error codes**: values of **err** in the callback of [on('fail')<sup>7+</sup>](#onfail7) and the values of the **failedReason** field returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9).<br> 26> 27> **Causes of download pause**: values of **pausedReason** returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9).<br> 28> 29> **Download task status code**: values of **status** returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9). 30 31| Name| Type| Value| Description| 32| -------- | -------- | -------- | -------- | 33| EXCEPTION_PERMISSION<sup>9+</sup> | number | 201 | (Universal error codes) Permission verification failed.| 34| EXCEPTION_PARAMCHECK<sup>9+</sup> | number | 401 | (Universal error codes) Parameter check failed.| 35| EXCEPTION_UNSUPPORTED<sup>9+</sup> | number | 801 | (Universal error codes) The device does not support this API.| 36| EXCEPTION_FILEIO<sup>9+</sup> | number | 13400001 | (Specific error codes) Abnormal file operation.| 37| EXCEPTION_FILEPATH<sup>9+</sup> | number | 13400002 | (Specific error codes) Abnormal file path.| 38| EXCEPTION_SERVICE<sup>9+</sup> | number | 13400003 | (Specific error codes) Abnormal service.| 39| EXCEPTION_OTHERS<sup>9+</sup> | number | 13499999 | (Specific error codes) Other errors.| 40| NETWORK_MOBILE<sup>6+</sup> | number | 0x00000001 | (Network type) Bit flag download allowed on a mobile network.| 41| NETWORK_WIFI<sup>6+</sup> | number | 0x00010000 | (Network type) Bit flag download allowed on a WLAN.| 42| ERROR_CANNOT_RESUME<sup>7+</sup> | number | 0 | (Download error codes) Failure to resume the download due to network errors.| 43| ERROR_DEVICE_NOT_FOUND<sup>7+</sup> | number | 1 | (Download error codes) Failure to find a storage device such as a memory card.| 44| ERROR_FILE_ALREADY_EXISTS<sup>7+</sup> | number | 2 | (Download error codes) Failure to download the file because it already exists.| 45| ERROR_FILE_ERROR<sup>7+</sup> | number | 3 | (Download error codes) File operation failed.| 46| ERROR_HTTP_DATA_ERROR<sup>7+</sup> | number | 4 | (Download error codes) HTTP transmission failed.| 47| ERROR_INSUFFICIENT_SPACE<sup>7+</sup> | number | 5 | (Download error codes) Insufficient storage space.| 48| ERROR_TOO_MANY_REDIRECTS<sup>7+</sup> | number | 6 | (Download error codes) Error caused by too many network redirections.| 49| ERROR_UNHANDLED_HTTP_CODE<sup>7+</sup> | number | 7 | (Download error codes) Unidentified HTTP code.| 50| ERROR_UNKNOWN<sup>7+</sup> | 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.)| 51| ERROR_OFFLINE<sup>9+</sup> | number | 9 | (Download error codes) No network connection.| 52| ERROR_UNSUPPORTED_NETWORK_TYPE<sup>9+</sup> | number | 10 | (Download error codes) Network type mismatch.| 53| PAUSED_QUEUED_FOR_WIFI<sup>7+</sup> | 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.| 54| PAUSED_WAITING_FOR_NETWORK<sup>7+</sup> | number | 1 | (Causes of download pause) Download paused due to a network connection problem, for example, network disconnection.| 55| PAUSED_WAITING_TO_RETRY<sup>7+</sup> | number | 2 | (Causes of download pause) Download paused and then retried.| 56| PAUSED_BY_USER<sup>9+</sup> | number | 3 | (Causes of download pause) The user paused the session.| 57| PAUSED_UNKNOWN<sup>7+</sup> | number | 4 | (Causes of download pause) Download paused due to unknown reasons.| 58| SESSION_SUCCESSFUL<sup>7+</sup> | number | 0 | (Download task status codes) Successful download.| 59| SESSION_RUNNING<sup>7+</sup> | number | 1 | (Download task status codes) Download in progress.| 60| SESSION_PENDING<sup>7+</sup> | number | 2 | (Download task status codes) Download pending.| 61| SESSION_PAUSED<sup>7+</sup> | number | 3 | (Download task status codes) Download paused.| 62| SESSION_FAILED<sup>7+</sup> | number | 4 | (Download task status codes) Download failure without retry.| 63 64 65## request.uploadFile<sup>9+</sup> 66 67uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> 68 69Uploads a file. This API uses a promise to return the result. HTTP is supported. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information. 70 71**Required permissions**: ohos.permission.INTERNET 72 73**System capability**: SystemCapability.MiscServices.Upload 74 75**Parameters** 76 77| Name| Type| Mandatory| Description| 78| -------- | -------- | -------- | -------- | 79| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 80| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 81 82 83**Return value** 84 85| Type| Description| 86| -------- | -------- | 87| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| 88 89**Error codes** 90 91For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 92 93| ID| Error Message| 94| -------- | -------- | 95| 201 | the permissions check fails | 96| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 97| 13400002 | bad file path. | 98 99**Example** 100 101 ```ts 102 import { BusinessError } from '@kit.BasicServicesKit'; 103 104 let uploadTask: request.UploadTask; 105 let uploadConfig: request.UploadConfig = { 106 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 107 header: { 'Accept': '*/*' }, 108 method: "POST", 109 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 110 data: [{ name: "name123", value: "123" }], 111 }; 112 try { 113 request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => { 114 uploadTask = data; 115 }).catch((err: BusinessError) => { 116 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 117 }); 118 } catch (err) { 119 console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`); 120 } 121 ``` 122 123> **NOTE** 124> 125> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 126 127 128## request.uploadFile<sup>9+</sup> 129 130uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void 131 132Uploads a file. This API uses an asynchronous callback to return the result. HTTP is supported. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information. 133 134**Required permissions**: ohos.permission.INTERNET 135 136**System capability**: SystemCapability.MiscServices.Upload 137 138**Parameters** 139 140| Name| Type| Mandatory| Description| 141| -------- | -------- | -------- | -------- | 142| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 143| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 144| callback | AsyncCallback<[UploadTask](#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.| 145 146**Error codes** 147 148For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 149 150| ID| Error Message| 151| -------- | -------- | 152| 201 | the permissions check fails | 153| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 154| 13400002 | bad file path. | 155 156**Example** 157 158 ```ts 159 import { BusinessError } from '@kit.BasicServicesKit'; 160 161 let uploadTask: request.UploadTask; 162 let uploadConfig: request.UploadConfig = { 163 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 164 header: { 'Accept': '*/*' }, 165 method: "POST", 166 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 167 data: [{ name: "name123", value: "123" }], 168 }; 169 try { 170 request.uploadFile(getContext(), uploadConfig, (err: BusinessError, data: request.UploadTask) => { 171 if (err) { 172 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 173 return; 174 } 175 uploadTask = data; 176 }); 177 } catch (err) { 178 console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`); 179 } 180 ``` 181 182> **NOTE** 183> 184> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 185 186## request.upload<sup>(deprecated)</sup> 187 188upload(config: UploadConfig): Promise<UploadTask> 189 190Uploads files. This API uses a promise to return the result. 191 192**Model restriction**: This API can be used only in the FA model. 193 194> **NOTE** 195> 196> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9) instead. 197 198**Required permissions**: ohos.permission.INTERNET 199 200**System capability**: SystemCapability.MiscServices.Upload 201 202**Parameters** 203 204| Name| Type| Mandatory| Description| 205| -------- | -------- | -------- | -------- | 206| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 207 208**Return value** 209 210| Type| Description| 211| -------- | -------- | 212| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| 213 214**Error codes** 215 216For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 217 218| ID| Error Message| 219| -------- | -------- | 220| 201 | the permissions check fails | 221 222**Example** 223 224 ```js 225 let uploadTask; 226 let uploadConfig = { 227 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 228 header: { 'Accept': '*/*' }, 229 method: "POST", 230 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 231 data: [{ name: "name123", value: "123" }], 232 }; 233 request.upload(uploadConfig).then((data) => { 234 uploadTask = data; 235 }).catch((err) => { 236 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 237 }) 238 ``` 239 240 241## request.upload<sup>(deprecated)</sup> 242 243upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void 244 245Uploads files. This API uses an asynchronous callback to return the result. 246 247**Model restriction**: This API can be used only in the FA model. 248 249> **NOTE** 250> 251> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1) instead. 252 253**Required permissions**: ohos.permission.INTERNET 254 255**System capability**: SystemCapability.MiscServices.Upload 256 257**Parameters** 258 259| Name| Type| Mandatory| Description| 260| -------- | -------- | -------- | -------- | 261| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 262| callback | AsyncCallback<[UploadTask](#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.| 263 264**Error codes** 265 266For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 267 268| ID| Error Message| 269| -------- | -------- | 270| 201 | the permissions check fails | 271 272**Example** 273 274 ```js 275 let uploadTask; 276 let uploadConfig = { 277 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 278 header: { 'Accept': '*/*' }, 279 method: "POST", 280 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 281 data: [{ name: "name123", value: "123" }], 282 }; 283 request.upload(uploadConfig, (err, data) => { 284 if (err) { 285 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 286 return; 287 } 288 uploadTask = data; 289 }); 290 ``` 291 292## UploadTask 293 294Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile<sup>9+</sup>](#requestuploadfile9) in promise mode or [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1) in callback mode. 295 296 297 298### on('progress') 299 300on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void 301 302Subscribes to upload progress events. This API uses an asynchronous callback to return the result. 303 304> **NOTE** 305> 306> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background. 307 308**System capability**: SystemCapability.MiscServices.Upload 309 310**Parameters** 311 312| Name| Type| Mandatory| Description| 313| -------- | -------- | -------- | -------- | 314| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| 315| callback | function | Yes| Callback used to return the size of the uploaded file and the total size of the file to upload.| 316 317 Parameters of the callback function 318 319| Name| Type| Mandatory| Description| 320| -------- | -------- | -------- | -------- | 321| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| 322| totalSize | number | Yes| Total size of the files to upload, in bytes.| 323 324**Error codes** 325 326For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 327 328| ID| Error Message| 329| -------- | -------- | 330| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 331 332**Example** 333 334<!--code_no_check--> 335 ```ts 336 let upProgressCallback = (uploadedSize: number, totalSize: number) => { 337 console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); 338 }; 339 uploadTask.on('progress', upProgressCallback); 340 ``` 341 342 343### on('headerReceive')<sup>7+</sup> 344 345on(type: 'headerReceive', callback: (header: object) => void): void 346 347Subscribes to HTTP response events for the upload task. This API uses a callback to return the result asynchronously. 348 349**System capability**: SystemCapability.MiscServices.Upload 350 351**Parameters** 352 353| Name| Type| Mandatory| Description| 354| -------- | -------- | -------- | -------- | 355| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response received).| 356| callback | function | Yes| Callback used to return the response content.| 357 358 Parameters of the callback function 359 360| Name| Type| Mandatory| Description| 361| -------- | -------- | -------- | -------- | 362| header | object | Yes| HTTP response.| 363 364**Error codes** 365 366For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 367 368| ID| Error Message| 369| -------- | -------- | 370| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 371 372**Example** 373 374<!--code_no_check--> 375 ```ts 376 let headerCallback = (headers: object) => { 377 console.info("upOnHeader headers:" + JSON.stringify(headers)); 378 }; 379 uploadTask.on('headerReceive', headerCallback); 380 ``` 381 382 383### on('complete' | 'fail')<sup>9+</sup> 384 385 on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; 386 387Subscribes to upload completion or failure events. This API uses an asynchronous callback to return the result. 388 389**System capability**: SystemCapability.MiscServices.Upload 390 391**Parameters** 392 393| Name| Type| Mandatory| Description| 394| -------- | -------- | -------- | -------- | 395| type | string | Yes| Callback types for subscribing to the upload events, including **'complete'\|'fail'**.<br>\- **'complete'**: the upload is complete.<br>\- **'fail'**: the upload fails. | 396| callback | Callback<Array<[TaskState](#taskstate9)>> | Yes| Callback used to return the result. | 397 398**Error codes** 399 400For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 401 402| ID| Error Message| 403| -------- | -------- | 404| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 405 406**Example** 407 408<!--code_no_check--> 409 ```ts 410 let upCompleteCallback = (taskStates: Array<request.TaskState>) => { 411 for (let i = 0; i < taskStates.length; i++) { 412 console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); 413 } 414 }; 415 uploadTask.on('complete', upCompleteCallback); 416 417 let upFailCallback = (taskStates: Array<request.TaskState>) => { 418 for (let i = 0; i < taskStates.length; i++) { 419 console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); 420 } 421 }; 422 uploadTask.on('fail', upFailCallback); 423 ``` 424 425 426### off('progress') 427 428off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void 429 430Unsubscribes from upload progress events. 431 432**System capability**: SystemCapability.MiscServices.Upload 433 434**Parameters** 435 436| Name| Type| Mandatory| Description| 437| -------- | -------- | -------- | -------- | 438| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| 439| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 440 441Parameters of the callback function 442 443| Name| Type| Mandatory| Description| 444| -------- | -------- | -------- | -------- | 445| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| 446| totalSize | number | Yes| Total size of the files to upload, in bytes.| 447**Error codes** 448 449For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 450 451| ID| Error Message| 452| -------- | -------- | 453| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 454 455**Example** 456 457<!--code_no_check--> 458 ```ts 459 let upProgressCallback1 = (uploadedSize: number, totalSize: number) => { 460 console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); 461 }; 462 let upProgressCallback2 = (uploadedSize: number, totalSize: number) => { 463 console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); 464 }; 465 uploadTask.on('progress', upProgressCallback1); 466 uploadTask.on('progress', upProgressCallback2); 467 // Unsubscribe from upProgressCallback1. 468 uploadTask.off('progress', upProgressCallback1); 469 // Unsubscribe from all callbacks of upload progress events. 470 uploadTask.off('progress'); 471 ``` 472 473 474### off('headerReceive')<sup>7+</sup> 475 476off(type: 'headerReceive', callback?: (header: object) => void): void 477 478Unsubscribes from HTTP response events for the upload task. 479 480**System capability**: SystemCapability.MiscServices.Upload 481 482**Parameters** 483 484| Name| Type| Mandatory| Description| 485| -------- | -------- | -------- | -------- | 486| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response received).| 487| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 488 489**Error codes** 490 491For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 492 493| ID| Error Message| 494| -------- | -------- | 495| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 496 497**Example** 498 499<!--code_no_check--> 500 ```ts 501 let headerCallback1 = (header: object) => { 502 console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); 503 }; 504 let headerCallback2 = (header: object) => { 505 console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); 506 }; 507 uploadTask.on('headerReceive', headerCallback1); 508 uploadTask.on('headerReceive', headerCallback2); 509 // Unsubscribe from headerCallback1. 510 uploadTask.off('headerReceive', headerCallback1); 511 // Unsubscribe from all callbacks of the HTTP header events for the upload task. 512 uploadTask.off('headerReceive'); 513 ``` 514 515### off('complete' | 'fail')<sup>9+</sup> 516 517 off(type:'complete' | 'fail', callback?: Callback<Array<TaskState>>): void; 518 519Unsubscribes from upload completion or failure events. 520 521**System capability**: SystemCapability.MiscServices.Upload 522 523**Parameters** 524 525| Name| Type| Mandatory| Description| 526| -------- | -------- | -------- | -------- | 527| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| 528| callback | Callback<Array<[TaskState](#taskstate9)>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 529 530**Error codes** 531 532For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 533 534| ID| Error Message| 535| -------- | -------- | 536| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 537 538**Example** 539 540<!--code_no_check--> 541 ```ts 542 let upCompleteCallback1 = (taskStates: Array<request.TaskState>) => { 543 console.info('Upload delete complete notification.'); 544 for (let i = 0; i < taskStates.length; i++) { 545 console.info('taskState:' + JSON.stringify(taskStates[i])); 546 } 547 }; 548 let upCompleteCallback2 = (taskStates: Array<request.TaskState>) => { 549 console.info('Upload delete complete notification.'); 550 for (let i = 0; i < taskStates.length; i++) { 551 console.info('taskState:' + JSON.stringify(taskStates[i])); 552 } 553 }; 554 uploadTask.on('complete', upCompleteCallback1); 555 uploadTask.on('complete', upCompleteCallback2); 556 // Unsubscribe from headerCallback1. 557 uploadTask.off('complete', upCompleteCallback1); 558 // Unsubscribe from all callbacks of the upload completion events. 559 uploadTask.off('complete'); 560 561 let upFailCallback1 = (taskStates: Array<request.TaskState>) => { 562 console.info('Upload delete fail notification.'); 563 for (let i = 0; i < taskStates.length; i++) { 564 console.info('taskState:' + JSON.stringify(taskStates[i])); 565 } 566 }; 567 let upFailCallback2 = (taskStates: Array<request.TaskState>) => { 568 console.info('Upload delete fail notification.'); 569 for (let i = 0; i < taskStates.length; i++) { 570 console.info('taskState:' + JSON.stringify(taskStates[i])); 571 } 572 }; 573 uploadTask.on('fail', upFailCallback1); 574 uploadTask.on('fail', upFailCallback2); 575 // Unsubscribe from headerCallback1. 576 uploadTask.off('fail', upFailCallback1); 577 // Unsubscribe from all callbacks of the upload failure events. 578 uploadTask.off('fail'); 579 ``` 580 581### delete<sup>9+</sup> 582delete(): Promise<boolean> 583 584Deletes this upload task. This API uses a promise to return the result. 585 586**Required permissions**: ohos.permission.INTERNET 587 588**System capability**: SystemCapability.MiscServices.Upload 589 590**Return value** 591 592| Type| Description| 593| -------- | -------- | 594| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 595 596**Error codes** 597 598For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 599 600| ID| Error Message| 601| -------- | -------- | 602| 201 | the permissions check fails | 603 604**Example** 605 606<!--code_no_check--> 607 ```ts 608 uploadTask.delete().then((result: boolean) => { 609 console.info('Succeeded in deleting the upload task.'); 610 }).catch((err: BusinessError) => { 611 console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); 612 }); 613 ``` 614 615> **NOTE** 616> 617> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 618 619 620### delete<sup>9+</sup> 621 622delete(callback: AsyncCallback<boolean>): void 623 624Deletes this upload task. This API uses an asynchronous callback to return the result. 625 626**Required permissions**: ohos.permission.INTERNET 627 628**System capability**: SystemCapability.MiscServices.Upload 629 630**Parameters** 631 632| Name| Type| Mandatory| Description| 633| -------- | -------- | -------- | -------- | 634| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 635 636**Error codes** 637 638For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 639 640| ID| Error Message| 641| -------- | -------- | 642| 201 | the permissions check fails | 643 644**Example** 645 646<!--code_no_check--> 647 ```ts 648 uploadTask.delete((err: BusinessError, result: boolean) => { 649 if (err) { 650 console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); 651 return; 652 } 653 console.info('Succeeded in deleting the upload task.'); 654 }); 655 ``` 656 657> **NOTE** 658> 659> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 660 661 662### remove<sup>(deprecated)</sup> 663 664remove(): Promise<boolean> 665 666Removes this upload task. This API uses a promise to return the result. 667 668> **NOTE** 669> 670> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9) instead. 671 672**Required permissions**: ohos.permission.INTERNET 673 674**System capability**: SystemCapability.MiscServices.Upload 675 676**Return value** 677 678| Type| Description| 679| -------- | -------- | 680| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 681 682**Error codes** 683 684For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 685 686| ID| Error Message| 687| -------- | -------- | 688| 201 | the permissions check fails | 689 690**Example** 691 692 ```js 693 uploadTask.remove().then((result) => { 694 console.info('Succeeded in removing the upload task.'); 695 }).catch((err) => { 696 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 697 }); 698 ``` 699 700 701### remove<sup>(deprecated)</sup> 702 703remove(callback: AsyncCallback<boolean>): void 704 705Removes this upload task. This API uses an asynchronous callback to return the result. 706 707> **NOTE** 708> 709> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-1) instead. 710 711**Required permissions**: ohos.permission.INTERNET 712 713**System capability**: SystemCapability.MiscServices.Upload 714 715**Parameters** 716 717| Name| Type| Mandatory| Description| 718| -------- | -------- | -------- | -------- | 719| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 720 721**Error codes** 722 723For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 724 725| ID| Error Message| 726| -------- | -------- | 727| 201 | the permissions check fails | 728 729**Example** 730 731 ```js 732 uploadTask.remove((err, result) => { 733 if (err) { 734 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 735 return; 736 } 737 if (result) { 738 console.info('Succeeded in removing the upload task.'); 739 } else { 740 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 741 } 742 }); 743 ``` 744 745## UploadConfig<sup>6+</sup> 746Describes the configuration of an upload task. 747 748**System capability**: SystemCapability.MiscServices.Upload 749 750| Name| Type| Mandatory| Description| 751| -------- | -------- | -------- | -------- | 752| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.| 753| header | Object | Yes| HTTP or HTTPS header added to an upload request.| 754| method | string | Yes| HTTP request method. The value can be **POST** or **PUT**. The default value is **POST**. Use the **PUT** method to modify resources and the **POST** method to add resources.| 755| index<sup>11+</sup> | number | No| Path index of the task. The default value is **0**.| 756| begins<sup>11+</sup> | number | No| File start point to read when the task begins. The default value is **0**. The value is a closed interval.| 757| ends<sup>11+</sup> | number | No| File start point to read when the task ends. The default value is **-1**. The value is a closed interval.| 758| files | Array<[File](#file)> | Yes| List of files to upload. The files are submitted in multipart/form-data format.| 759| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| 760 761## TaskState<sup>9+</sup> 762Implements a **TaskState** object, which is the callback parameter of the [on('complete' | 'fail')<sup>9+</sup>](#oncomplete--fail9) and [off('complete' | 'fail')<sup>9+</sup>](#offcomplete--fail9) APIs. 763 764**System capability**: SystemCapability.MiscServices.Upload 765 766| Name| Type| Mandatory| Description | 767| -------- | -------- | -------- |-------------------------------------------------------------------------------------------------------------------------------------------| 768| path | string | Yes| File path. | 769| 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.create<sup>10+</sup>](#requestagentcreate10-1) and handle exceptions based on standard error codes.| 770| message | string | Yes| Description of the upload task result. | 771 772The following table describes the enum values of **responseCode**. 773 774| Result Code| Description | 775|-----|------------------------------------| 776| 0 | Upload success. | 777| 5 | Task suspended or stopped proactively. | 778| 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. | 779| 7 | No network connection. Check whether the device is connected to the network. | 780| 8 | Network mismatch. Check whether the current network type matches the network type required by the task. | 781| 10 | Failed to create the HTTP request. Verify the parameters or try again. | 782| 12 | Request timeout. Verify the parameter configuration or the network connection, or try again. | 783| 13 | Connection failed. Verify the parameter configuration or the network connection, or try again. | 784| 14 | Request failed. Verify the parameter configuration or the network connection, or try again. | 785| 15 | Upload failed. Verify the parameter configuration or the network connection, or try again. | 786| 16 | Redirection failed. Verify the parameter configuration or the network connection, or try again. | 787| 17 | Protocol error. The server returns a 4XX or 5XX status code. Verify the parameter configuration and try again.| 788| 20 | Other errors. Verify the parameter configuration or the network connection, or try again. | 789 790## File 791Defines the file list in [UploadConfig<sup>6+</sup>](#uploadconfig6). 792 793**System capability**: SystemCapability.MiscServices.Download 794 795| Name| Type| Mandatory| Description| 796| -------- | -------- | -------- | -------- | 797| filename | string | Yes| File name in the header when **multipart** is used.| 798| name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| 799| uri | string | Yes| Local path for storing files.<br>Only internal protocols are supported in the path. Therefore, **internal://cache/**, that is, **context.cacheDir** of the caller (namely, cache directory of the input **context**), must be included in the path,<br>for example, **internal://cache/path/to/file.txt**.| 800| type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| 801 802 803## RequestData 804Defines the form data in [UploadConfig<sup>6+</sup>](#uploadconfig6). 805 806**System capability**: SystemCapability.MiscServices.Download 807 808| Name| Type| Mandatory| Description| 809| -------- | -------- | -------- | -------- | 810| name | string | Yes| Name of a form element.| 811| value | string | Yes| Value of a form element.| 812 813## request.downloadFile<sup>9+</sup> 814 815downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> 816 817Downloads a file. This API uses a promise to return the result. HTTP is supported. You can use [on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')<sup>7+</sup>](#onfail7) to obtain the task download error information. 818 819**Required permissions**: ohos.permission.INTERNET 820 821**System capability**: SystemCapability.MiscServices.Download 822 823**Parameters** 824 825| Name| Type| Mandatory| Description| 826| -------- | -------- | -------- | -------- | 827| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 828| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 829 830**Return value** 831 832| Type| Description| 833| -------- | -------- | 834| Promise<[DownloadTask](#downloadtask)> | Promise used to return the **DownloadTask** object.| 835 836**Error codes** 837 838For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 839 840| ID| Error Message| 841| -------- | -------- | 842| 201 | the permissions check fails | 843| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 844| 13400001 | file operation error. | 845| 13400002 | bad file path. | 846| 13400003 | task service ability error. | 847 848**Example** 849 850 ```ts 851import { BusinessError } from '@kit.BasicServicesKit'; 852 853 try { 854 // Replace the URL with the HTTP address of the real server. 855 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 856 let downloadTask: request.DownloadTask = data; 857 }).catch((err: BusinessError) => { 858 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 859 }) 860 } catch (err) { 861 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 862 } 863 ``` 864 865> **NOTE** 866> 867> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 868 869 870## request.downloadFile<sup>9+</sup> 871 872downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; 873 874Downloads a file. This API uses an asynchronous callback to return the result. HTTP is supported. You can use [on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')<sup>7+</sup>](#onfail7) to obtain the task download error information. 875 876**Required permissions**: ohos.permission.INTERNET 877 878**System capability**: SystemCapability.MiscServices.Download 879 880**Parameters** 881 882| Name| Type| Mandatory| Description| 883| -------- | -------- | -------- | -------- | 884| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 885| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 886| callback | AsyncCallback<[DownloadTask](#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.| 887 888**Error codes** 889 890For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 891 892| ID| Error Message| 893| -------- | -------- | 894| 201 | the permissions check fails | 895| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 896| 13400001 | file operation error. | 897| 13400002 | bad file path. | 898| 13400003 | task service ability error. | 899 900**Example** 901 902 ```ts 903import { BusinessError } from '@kit.BasicServicesKit'; 904 905 try { 906 // Replace the URL with the HTTP address of the real server. 907 request.downloadFile(getContext(), { 908 url: 'https://xxxx/xxxxx.hap', 909 filePath: 'xxx/xxxxx.hap' 910 }, (err: BusinessError, data: request.DownloadTask) => { 911 if (err) { 912 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 913 return; 914 } 915 let downloadTask: request.DownloadTask = data; 916 }); 917 } catch (err) { 918 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 919 } 920 ``` 921 922> **NOTE** 923> 924> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 925 926## request.download<sup>(deprecated)</sup> 927 928download(config: DownloadConfig): Promise<DownloadTask> 929 930Downloads files. This API uses a promise to return the result. 931 932> **NOTE** 933> 934> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9) instead. 935 936**Model restriction**: This API can be used only in the FA model. 937 938**Required permissions**: ohos.permission.INTERNET 939 940**System capability**: SystemCapability.MiscServices.Download 941 942**Parameters** 943 944| Name| Type| Mandatory| Description| 945| -------- | -------- | -------- | -------- | 946| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 947 948**Return value** 949 950| Type| Description| 951| -------- | -------- | 952| Promise<[DownloadTask](#downloadtask)> | Promise used to return the **DownloadTask** object.| 953 954**Error codes** 955 956For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 957 958| ID| Error Message| 959| -------- | -------- | 960| 201 | the permissions check fails | 961 962**Example** 963 964 ```js 965 let downloadTask; 966 // Replace the URL with the HTTP address of the real server. 967 request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { 968 downloadTask = data; 969 }).catch((err) => { 970 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 971 }) 972 ``` 973 974 975## request.download<sup>(deprecated)</sup> 976 977download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void 978 979Downloads files. This API uses an asynchronous callback to return the result. 980 981> **NOTE** 982> 983> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1) instead. 984 985**Model restriction**: This API can be used only in the FA model. 986 987**Required permissions**: ohos.permission.INTERNET 988 989**System capability**: SystemCapability.MiscServices.Download 990 991**Parameters** 992 993| Name| Type| Mandatory| Description| 994| -------- | -------- | -------- | -------- | 995| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 996| callback | AsyncCallback<[DownloadTask](#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.| 997 998**Error codes** 999 1000For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1001 1002| ID| Error Message| 1003| -------- | -------- | 1004| 201 | the permissions check fails | 1005 1006**Example** 1007 1008 ```js 1009 let downloadTask; 1010 // Replace the URL with the HTTP address of the real server. 1011 request.download({ url: 'https://xxxx/xxxxx.hap', 1012 filePath: 'xxx/xxxxx.hap'}, (err, data) => { 1013 if (err) { 1014 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1015 return; 1016 } 1017 downloadTask = data; 1018 }); 1019 ``` 1020 1021## DownloadTask 1022 1023Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile<sup>9+</sup>](#requestdownloadfile9) in promise mode or [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1) in callback mode. 1024 1025 1026### on('progress') 1027 1028on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void 1029 1030Subscribes to download progress events. This API uses an asynchronous callback to return the result. 1031 1032> **NOTE** 1033> 1034> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background. 1035 1036**System capability**: SystemCapability.MiscServices.Download 1037 1038**Parameters** 1039 1040| Name| Type| Mandatory| Description| 1041| -------- | -------- | -------- | -------- | 1042| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| 1043| callback | function | Yes| Callback used to return the size of the uploaded file and the total size of the file to download.| 1044 1045 Parameters of the callback function 1046 1047| Name| Type| Mandatory| Description | 1048| -------- | -------- | -------- |-------------------------------------------------------------------------| 1049| receivedSize | number | Yes| Current download progress, in bytes. | 1050| 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**.| 1051 1052**Error codes** 1053 1054For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1055 1056| ID| Error Message| 1057| -------- | -------- | 1058| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1059 1060**Example** 1061 1062 ```ts 1063import { BusinessError } from '@kit.BasicServicesKit'; 1064 1065 try { 1066 // Replace the URL with the HTTP address of the real server. 1067 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1068 let downloadTask: request.DownloadTask = data; 1069 let progressCallback = (receivedSize: number, totalSize: number) => { 1070 console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); 1071 }; 1072 downloadTask.on('progress', progressCallback); 1073 }).catch((err: BusinessError) => { 1074 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1075 }) 1076 } catch (err) { 1077 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1078 } 1079 ``` 1080 1081 1082### off('progress') 1083 1084off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void 1085 1086Unsubscribes from download progress events. 1087 1088**System capability**: SystemCapability.MiscServices.Download 1089 1090**Parameters** 1091 1092| Name| Type| Mandatory| Description| 1093| -------- | -------- | -------- | -------- | 1094| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| 1095| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 1096 1097 Parameters of the callback function 1098 1099| Name| Type| Mandatory| Description | 1100| -------- | -------- | -------- |-------------------------------------------------------------------------| 1101| receivedSize | number | Yes| Current download progress, in bytes. | 1102| 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**.| 1103 1104**Error codes** 1105 1106For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1107 1108| ID| Error Message| 1109| -------- | -------- | 1110| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1111 1112**Example** 1113 1114 ```ts 1115import { BusinessError } from '@kit.BasicServicesKit'; 1116 1117try { 1118 // Replace the URL with the HTTP address of the real server. 1119 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1120 let downloadTask: request.DownloadTask = data; 1121 let progressCallback1 = (receivedSize: number, totalSize: number) => { 1122 console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); 1123 }; 1124 let progressCallback2 = (receivedSize: number, totalSize: number) => { 1125 console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); 1126 }; 1127 downloadTask.on('progress', progressCallback1); 1128 downloadTask.on('progress', progressCallback2); 1129 // Unsubscribe from progressCallback1. 1130 downloadTask.off('progress', progressCallback1); 1131 // Unsubscribe from all callbacks of download progress events. 1132 downloadTask.off('progress'); 1133 }).catch((err: BusinessError) => { 1134 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1135 }) 1136} catch (err) { 1137 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1138} 1139 ``` 1140 1141 1142### on('complete'|'pause'|'remove')<sup>7+</sup> 1143 1144on(type: 'complete'|'pause'|'remove', callback:() => void): void 1145 1146Subscribes to download events. This API uses a callback to return the result asynchronously. 1147 1148**System capability**: SystemCapability.MiscServices.Download 1149 1150**Parameters** 1151 1152| Name| Type| Mandatory| Description| 1153| -------- | -------- | -------- | -------- | 1154| type | string | Yes| Type of the event to subscribe to.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.| 1155| callback | function | Yes| Callback used to return the result.| 1156 1157**Error codes** 1158 1159For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1160 1161| ID| Error Message| 1162| -------- | -------- | 1163| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1164 1165**Example** 1166 1167 ```ts 1168import { BusinessError } from '@kit.BasicServicesKit'; 1169 1170try { 1171 // Replace the URL with the HTTP address of the real server. 1172 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1173 let downloadTask: request.DownloadTask = data; 1174 let completeCallback = () => { 1175 console.info('Download task completed.'); 1176 }; 1177 downloadTask.on('complete', completeCallback); 1178 1179 let pauseCallback = () => { 1180 console.info('Download task pause.'); 1181 }; 1182 downloadTask.on('pause', pauseCallback); 1183 1184 let removeCallback = () => { 1185 console.info('Download task remove.'); 1186 }; 1187 downloadTask.on('remove', removeCallback); 1188 }).catch((err: BusinessError) => { 1189 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1190 }) 1191} catch (err) { 1192 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1193} 1194 ``` 1195 1196 1197### off('complete'|'pause'|'remove')<sup>7+</sup> 1198 1199off(type: 'complete'|'pause'|'remove', callback?: () => void): void 1200 1201Unsubscribes from download events. 1202 1203**System capability**: SystemCapability.MiscServices.Download 1204 1205**Parameters** 1206 1207| Name| Type| Mandatory| Description| 1208| -------- | -------- | -------- | -------- | 1209| type | string | Yes| Type of the event to unsubscribe from.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.| 1210| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 1211 1212**Error codes** 1213 1214For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1215 1216| ID| Error Message| 1217| -------- | -------- | 1218| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1219 1220**Example** 1221 1222 ```ts 1223import { BusinessError } from '@kit.BasicServicesKit'; 1224 1225try { 1226 // Replace the URL with the HTTP address of the real server. 1227 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1228 let downloadTask: request.DownloadTask = data; 1229 let completeCallback1 = () => { 1230 console.info('Download delete complete notification.'); 1231 }; 1232 let completeCallback2 = () => { 1233 console.info('Download delete complete notification.'); 1234 }; 1235 downloadTask.on('complete', completeCallback1); 1236 downloadTask.on('complete', completeCallback2); 1237 // Unsubscribe from completeCallback1. 1238 downloadTask.off('complete', completeCallback1); 1239 // Unsubscribe from all callbacks of the download completion events. 1240 downloadTask.off('complete'); 1241 1242 let pauseCallback1 = () => { 1243 console.info('Download delete pause notification.'); 1244 }; 1245 let pauseCallback2 = () => { 1246 console.info('Download delete pause notification.'); 1247 }; 1248 downloadTask.on('pause', pauseCallback1); 1249 downloadTask.on('pause', pauseCallback2); 1250 // Unsubscribe from pauseCallback1. 1251 downloadTask.off('pause', pauseCallback1); 1252 // Unsubscribe from all callbacks of the download pause events. 1253 downloadTask.off('pause'); 1254 1255 let removeCallback1 = () => { 1256 console.info('Download delete remove notification.'); 1257 }; 1258 let removeCallback2 = () => { 1259 console.info('Download delete remove notification.'); 1260 }; 1261 downloadTask.on('remove', removeCallback1); 1262 downloadTask.on('remove', removeCallback2); 1263 // Unsubscribe from removeCallback1. 1264 downloadTask.off('remove', removeCallback1); 1265 // Unsubscribe from all callbacks of the download removal events. 1266 downloadTask.off('remove'); 1267 }).catch((err: BusinessError) => { 1268 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1269 }) 1270} catch (err) { 1271 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1272} 1273 1274 ``` 1275 1276 1277### on('fail')<sup>7+</sup> 1278 1279on(type: 'fail', callback: (err: number) => void): void 1280 1281Subscribes to download failure events. This API uses an asynchronous callback to return the result. 1282 1283**System capability**: SystemCapability.MiscServices.Download 1284 1285**Parameters** 1286 1287| Name| Type| Mandatory| Description| 1288| -------- | -------- | -------- | -------- | 1289| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| 1290| callback | function | Yes| Callback for the download task failure event.| 1291 1292 Parameters of the callback function 1293 1294| Name| Type| Mandatory| Description| 1295| -------- | -------- | -------- | -------- | 1296| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#constants).| 1297 1298**Error codes** 1299 1300For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1301 1302| ID| Error Message| 1303| -------- | -------- | 1304| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1305 1306**Example** 1307 1308 ```ts 1309import { BusinessError } from '@kit.BasicServicesKit'; 1310 1311try { 1312 // Replace the URL with the HTTP address of the real server. 1313 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1314 let downloadTask: request.DownloadTask = data; 1315 let failCallback = (err: number) => { 1316 console.error(`Failed to download the task. Code: ${err}`); 1317 }; 1318 downloadTask.on('fail', failCallback); 1319 }).catch((err: BusinessError) => { 1320 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1321 }) 1322} catch (err) { 1323 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1324} 1325 ``` 1326 1327 1328### off('fail')<sup>7+</sup> 1329 1330off(type: 'fail', callback?: (err: number) => void): void 1331 1332Unsubscribes from download failure events. 1333 1334**System capability**: SystemCapability.MiscServices.Download 1335 1336**Parameters** 1337 1338| Name| Type| Mandatory| Description| 1339| -------- | -------- | -------- | -------- | 1340| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| 1341| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 1342 1343**Error codes** 1344 1345For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1346 1347| ID| Error Message| 1348| -------- | -------- | 1349| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1350 1351**Example** 1352 1353 ```ts 1354import { BusinessError } from '@kit.BasicServicesKit'; 1355 1356try { 1357 // Replace the URL with the HTTP address of the real server. 1358 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1359 let downloadTask: request.DownloadTask = data; 1360 let failCallback1 = (err: number) => { 1361 console.error(`Failed to download the task. Code: ${err}`); 1362 }; 1363 let failCallback2 = (err: number) => { 1364 console.error(`Failed to download the task. Code: ${err}`); 1365 }; 1366 downloadTask.on('fail', failCallback1); 1367 downloadTask.on('fail', failCallback2); 1368 // Unsubscribe from failCallback1. 1369 downloadTask.off('fail', failCallback1); 1370 // Unsubscribe from all callbacks of the download failure events. 1371 downloadTask.off('fail'); 1372 }).catch((err: BusinessError) => { 1373 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1374 }) 1375} catch (err) { 1376 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1377} 1378 ``` 1379 1380### delete<sup>9+</sup> 1381 1382delete(): Promise<boolean> 1383 1384Deletes this download task. This API uses a promise to return the result. 1385 1386**Required permissions**: ohos.permission.INTERNET 1387 1388**System capability**: SystemCapability.MiscServices.Download 1389 1390**Return value** 1391 1392| Type| Description| 1393| -------- | -------- | 1394| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1395 1396**Error codes** 1397 1398For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1399 1400| ID| Error Message| 1401| -------- | -------- | 1402| 201 | the permissions check fails | 1403 1404**Example** 1405 1406 ```ts 1407import { BusinessError } from '@kit.BasicServicesKit'; 1408 1409try { 1410 // Replace the URL with the HTTP address of the real server. 1411 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1412 let downloadTask: request.DownloadTask = data; 1413 downloadTask.delete().then((result: boolean) => { 1414 console.info('Succeeded in removing the download task.'); 1415 }).catch((err: BusinessError) => { 1416 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1417 }); 1418 }).catch((err: BusinessError) => { 1419 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1420 }) 1421} catch (err) { 1422 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1423} 1424 ``` 1425 1426> **NOTE** 1427> 1428> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1429 1430 1431### delete<sup>9+</sup> 1432 1433delete(callback: AsyncCallback<boolean>): void 1434 1435Deletes this download task. This API uses an asynchronous callback to return the result. 1436 1437**Required permissions**: ohos.permission.INTERNET 1438 1439**System capability**: SystemCapability.MiscServices.Download 1440 1441**Parameters** 1442 1443| Name| Type| Mandatory| Description| 1444| -------- | -------- | -------- | -------- | 1445| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1446 1447**Error codes** 1448 1449For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1450 1451| ID| Error Message| 1452| -------- | -------- | 1453| 201 | the permissions check fails | 1454 1455**Example** 1456 1457 ```ts 1458import { BusinessError } from '@kit.BasicServicesKit'; 1459 1460try { 1461 // Replace the URL with the HTTP address of the real server. 1462 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1463 let downloadTask: request.DownloadTask = data; 1464 downloadTask.delete((err: BusinessError, result: boolean) => { 1465 if (err) { 1466 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1467 return; 1468 } 1469 console.info('Succeeded in removing the download task.'); 1470 }); 1471 }).catch((err: BusinessError) => { 1472 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1473 }) 1474} catch (err) { 1475 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1476} 1477 ``` 1478 1479> **NOTE** 1480> 1481> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1482 1483 1484### getTaskInfo<sup>9+</sup> 1485 1486getTaskInfo(): Promise<DownloadInfo> 1487 1488Obtains the information about this download task. This API uses a promise to return the result. 1489 1490**Required permissions**: ohos.permission.INTERNET 1491 1492**System capability**: SystemCapability.MiscServices.Download 1493 1494**Return value** 1495 1496| Type| Description| 1497| -------- | -------- | 1498| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the **DownloadInfo** object.| 1499 1500**Error codes** 1501 1502For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1503 1504| ID| Error Message| 1505| -------- | -------- | 1506| 201 | the permissions check fails | 1507 1508**Example** 1509 1510 ```ts 1511import { BusinessError } from '@kit.BasicServicesKit'; 1512 1513try { 1514 // Replace the URL with the HTTP address of the real server. 1515 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1516 let downloadTask: request.DownloadTask = data; 1517 downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => { 1518 console.info('Succeeded in querying the download task') 1519 }).catch((err: BusinessError) => { 1520 console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) 1521 }); 1522 }).catch((err: BusinessError) => { 1523 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1524 }) 1525} catch (err) { 1526 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1527} 1528 ``` 1529 1530> **NOTE** 1531> 1532> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1533 1534 1535### getTaskInfo<sup>9+</sup> 1536 1537getTaskInfo(callback: AsyncCallback<DownloadInfo>): void 1538 1539Obtains this download task. This API uses an asynchronous callback to return the result. 1540 1541**Required permissions**: ohos.permission.INTERNET 1542 1543**System capability**: SystemCapability.MiscServices.Download 1544 1545**Parameters** 1546 1547| Name| Type| Mandatory| Description| 1548| -------- | -------- | -------- | -------- | 1549| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | 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.| 1550 1551**Error codes** 1552 1553For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1554 1555| ID| Error Message| 1556| -------- | -------- | 1557| 201 | the permissions check fails | 1558 1559**Example** 1560 1561 ```ts 1562import { BusinessError } from '@kit.BasicServicesKit'; 1563 1564try { 1565 // Replace the URL with the HTTP address of the real server. 1566 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1567 let downloadTask: request.DownloadTask = data; 1568 downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => { 1569 if (err) { 1570 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 1571 } else { 1572 console.info('Succeeded in querying the download mimeType'); 1573 } 1574 }); 1575 }).catch((err: BusinessError) => { 1576 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1577 }) 1578} catch (err) { 1579 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1580} 1581 ``` 1582 1583> **NOTE** 1584> 1585> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1586 1587 1588### getTaskMimeType<sup>9+</sup> 1589 1590getTaskMimeType(): Promise<string> 1591 1592Obtains **MimeType** (that is, media type of resources) of a download task. This API uses a promise to return the result. 1593 1594**Required permissions**: ohos.permission.INTERNET 1595 1596**System capability**: SystemCapability.MiscServices.Download 1597 1598**Return value** 1599 1600| Type| Description| 1601| -------- | -------- | 1602| Promise<string> | Promise used to return the **MimeType** object.| 1603 1604**Error codes** 1605 1606For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1607 1608| ID| Error Message| 1609| -------- | -------- | 1610| 201 | the permissions check fails | 1611 1612**Example** 1613 1614 ```ts 1615import { BusinessError } from '@kit.BasicServicesKit'; 1616 1617try { 1618 // Replace the URL with the HTTP address of the real server. 1619 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1620 let downloadTask: request.DownloadTask = data; 1621 downloadTask.getTaskMimeType().then((data: string) => { 1622 console.info('Succeeded in querying the download MimeType'); 1623 }).catch((err: BusinessError) => { 1624 console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) 1625 }); 1626 }).catch((err: BusinessError) => { 1627 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1628 }) 1629} catch (err) { 1630 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1631} 1632 ``` 1633 1634> **NOTE** 1635> 1636> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1637 1638 1639### getTaskMimeType<sup>9+</sup> 1640 1641getTaskMimeType(callback: AsyncCallback<string>): void; 1642 1643Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. 1644 1645**Required permissions**: ohos.permission.INTERNET 1646 1647**System capability**: SystemCapability.MiscServices.Download 1648 1649**Parameters** 1650 1651| Name| Type| Mandatory| Description| 1652| -------- | -------- | -------- | -------- | 1653| 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.| 1654 1655**Error codes** 1656 1657For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1658 1659| ID| Error Message| 1660| -------- | -------- | 1661| 201 | the permissions check fails | 1662 1663**Example** 1664 1665 ```ts 1666import { BusinessError } from '@kit.BasicServicesKit'; 1667 1668try { 1669 // Replace the URL with the HTTP address of the real server. 1670 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1671 let downloadTask: request.DownloadTask = data; 1672 downloadTask.getTaskMimeType((err: BusinessError, data: string) => { 1673 if (err) { 1674 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 1675 } else { 1676 console.info('Succeeded in querying the download mimeType'); 1677 } 1678 }); 1679 }).catch((err: BusinessError) => { 1680 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1681 }) 1682} catch (err) { 1683 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1684} 1685 ``` 1686 1687> **NOTE** 1688> 1689> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1690 1691 1692### suspend<sup>9+</sup> 1693 1694suspend(): Promise<boolean> 1695 1696Suspends this download task. This API uses a promise to return the result. 1697 1698**Required permissions**: ohos.permission.INTERNET 1699 1700**System capability**: SystemCapability.MiscServices.Download 1701 1702**Return value** 1703 1704| Type| Description| 1705| -------- | -------- | 1706| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1707 1708**Error codes** 1709 1710For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1711 1712| ID| Error Message| 1713| -------- | -------- | 1714| 201 | the permissions check fails | 1715 1716**Example** 1717 1718 ```ts 1719import { BusinessError } from '@kit.BasicServicesKit'; 1720 1721try { 1722 // Replace the URL with the HTTP address of the real server. 1723 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1724 let downloadTask: request.DownloadTask = data; 1725 downloadTask.suspend().then((result: boolean) => { 1726 console.info('Succeeded in pausing the download task.'); 1727 }).catch((err: BusinessError) => { 1728 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 1729 }); 1730 }).catch((err: BusinessError) => { 1731 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1732 }) 1733} catch (err) { 1734 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1735} 1736 ``` 1737 1738> **NOTE** 1739> 1740> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1741 1742 1743### suspend<sup>9+</sup> 1744 1745suspend(callback: AsyncCallback<boolean>): void 1746 1747Suspends this download task. This API uses an asynchronous callback to return the result. 1748 1749**Required permissions**: ohos.permission.INTERNET 1750 1751**System capability**: SystemCapability.MiscServices.Download 1752 1753**Parameters** 1754 1755| Name| Type| Mandatory| Description| 1756| -------- | -------- | -------- | -------- | 1757| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1758 1759**Error codes** 1760 1761For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1762 1763| ID| Error Message| 1764| -------- | -------- | 1765| 201 | the permissions check fails | 1766 1767**Example** 1768 1769 ```ts 1770import { BusinessError } from '@kit.BasicServicesKit'; 1771 1772try { 1773 // Replace the URL with the HTTP address of the real server. 1774 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1775 let downloadTask: request.DownloadTask = data; 1776 downloadTask.suspend((err: BusinessError, result: boolean) => { 1777 if (err) { 1778 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 1779 return; 1780 } 1781 console.info('Succeeded in pausing the download task.'); 1782 }); 1783 }).catch((err: BusinessError) => { 1784 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1785 }) 1786} catch (err) { 1787 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1788} 1789 ``` 1790 1791> **NOTE** 1792> 1793> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1794 1795 1796### restore<sup>9+</sup> 1797 1798restore(): Promise<boolean> 1799 1800Restores this download task. This API uses a promise to return the result. 1801 1802**Required permissions**: ohos.permission.INTERNET 1803 1804**System capability**: SystemCapability.MiscServices.Download 1805 1806**Return value** 1807 1808| Type| Description| 1809| -------- | -------- | 1810| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1811 1812**Error codes** 1813 1814For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1815 1816| ID| Error Message| 1817| -------- | -------- | 1818| 201 | the permissions check fails | 1819 1820**Example** 1821 1822 ```ts 1823import { BusinessError } from '@kit.BasicServicesKit'; 1824 1825try { 1826 // Replace the URL with the HTTP address of the real server. 1827 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1828 let downloadTask: request.DownloadTask = data; 1829 downloadTask.restore().then((result: boolean) => { 1830 console.info('Succeeded in resuming the download task.') 1831 }).catch((err: BusinessError) => { 1832 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 1833 }); 1834 }).catch((err: BusinessError) => { 1835 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1836 }) 1837} catch (err) { 1838 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1839} 1840 ``` 1841 1842> **NOTE** 1843> 1844> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1845 1846 1847### restore<sup>9+</sup> 1848 1849restore(callback: AsyncCallback<boolean>): void 1850 1851Restores this download task. This API uses an asynchronous callback to return the result. 1852 1853**Required permissions**: ohos.permission.INTERNET 1854 1855**System capability**: SystemCapability.MiscServices.Download 1856 1857**Parameters** 1858 1859| Name| Type| Mandatory| Description| 1860| -------- | -------- | -------- | -------- | 1861| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1862 1863**Error codes** 1864 1865For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1866 1867| ID| Error Message| 1868| -------- | -------- | 1869| 201 | the permissions check fails | 1870 1871**Example** 1872 1873 ```ts 1874import { BusinessError } from '@kit.BasicServicesKit'; 1875 1876try { 1877 // Replace the URL with the HTTP address of the real server. 1878 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1879 let downloadTask: request.DownloadTask = data; 1880 downloadTask.restore((err: BusinessError, result: boolean) => { 1881 if (err) { 1882 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 1883 return; 1884 } 1885 console.info('Succeeded in resuming the download task.'); 1886 }); 1887 }).catch((err: BusinessError) => { 1888 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1889 }) 1890} catch (err) { 1891 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1892} 1893 ``` 1894 1895> **NOTE** 1896> 1897> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1898 1899 1900### remove<sup>(deprecated)</sup> 1901 1902remove(): Promise<boolean> 1903 1904Removes this download task. This API uses a promise to return the result. 1905 1906> **NOTE** 1907> 1908> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-2) instead. 1909 1910**Required permissions**: ohos.permission.INTERNET 1911 1912**System capability**: SystemCapability.MiscServices.Download 1913 1914**Return value** 1915 1916| Type| Description| 1917| -------- | -------- | 1918| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1919 1920**Error codes** 1921 1922For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1923 1924| ID| Error Message| 1925| -------- | -------- | 1926| 201 | the permissions check fails | 1927 1928**Example** 1929 1930 ```js 1931 downloadTask.remove().then((result) => { 1932 console.info('Succeeded in removing the download task.'); 1933 }).catch ((err) => { 1934 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1935 }); 1936 ``` 1937 1938 1939### remove<sup>(deprecated)</sup> 1940 1941remove(callback: AsyncCallback<boolean>): void 1942 1943Removes this download task. This API uses an asynchronous callback to return the result. 1944 1945> **NOTE** 1946> 1947> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-3) instead. 1948 1949**Required permissions**: ohos.permission.INTERNET 1950 1951**System capability**: SystemCapability.MiscServices.Download 1952 1953**Parameters** 1954 1955| Name| Type| Mandatory| Description| 1956| -------- | -------- | -------- | -------- | 1957| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1958 1959**Error codes** 1960 1961For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1962 1963| ID| Error Message| 1964| -------- | -------- | 1965| 201 | the permissions check fails | 1966 1967**Example** 1968 1969 ```js 1970 downloadTask.remove((err, result)=>{ 1971 if(err) { 1972 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1973 return; 1974 } 1975 console.info('Succeeded in removing the download task.'); 1976 }); 1977 ``` 1978 1979 1980### query<sup>(deprecated)</sup> 1981 1982query(): Promise<DownloadInfo> 1983 1984Queries this download task. This API uses a promise to return the result. 1985 1986> **NOTE** 1987> 1988> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9) instead. 1989 1990**Required permissions**: ohos.permission.INTERNET 1991 1992**System capability**: SystemCapability.MiscServices.Download 1993 1994**Return value** 1995 1996| Type| Description| 1997| -------- | -------- | 1998| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the **DownloadInfo** object.| 1999 2000**Error codes** 2001 2002For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2003 2004| ID| Error Message| 2005| -------- | -------- | 2006| 201 | the permissions check fails | 2007 2008**Example** 2009 2010 ```js 2011 downloadTask.query().then((downloadInfo) => { 2012 console.info('Succeeded in querying the download task.') 2013 }) .catch((err) => { 2014 console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) 2015 }); 2016 ``` 2017 2018 2019### query<sup>(deprecated)</sup> 2020 2021query(callback: AsyncCallback<DownloadInfo>): void 2022 2023Queries this download task. This API uses an asynchronous callback to return the result. 2024 2025> **NOTE** 2026> 2027> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9-1) instead. 2028 2029**Required permissions**: ohos.permission.INTERNET 2030 2031**System capability**: SystemCapability.MiscServices.Download 2032 2033**Parameters** 2034 2035| Name| Type| Mandatory| Description| 2036| -------- | -------- | -------- | -------- | 2037| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | 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.| 2038 2039**Error codes** 2040 2041For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2042 2043| ID| Error Message| 2044| -------- | -------- | 2045| 201 | the permissions check fails | 2046 2047**Example** 2048 2049 ```js 2050 downloadTask.query((err, downloadInfo)=>{ 2051 if(err) { 2052 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 2053 } else { 2054 console.info('Succeeded in querying the download task.'); 2055 } 2056 }); 2057 ``` 2058 2059 2060### queryMimeType<sup>(deprecated)</sup> 2061 2062queryMimeType(): Promise<string> 2063 2064Queries the **MimeType** of this download task. This API uses a promise to return the result. 2065 2066> **NOTE** 2067> 2068> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9) instead. 2069 2070**Required permissions**: ohos.permission.INTERNET 2071 2072**System capability**: SystemCapability.MiscServices.Download 2073 2074**Return value** 2075 2076| Type| Description| 2077| -------- | -------- | 2078| Promise<string> | Promise used to return the **MimeType** object.| 2079 2080**Error codes** 2081 2082For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2083 2084| ID| Error Message| 2085| -------- | -------- | 2086| 201 | the permissions check fails | 2087 2088**Example** 2089 2090 ```js 2091 downloadTask.queryMimeType().then((data) => { 2092 console.info('Succeeded in querying the download MimeType.'); 2093 }).catch((err) => { 2094 console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) 2095 }); 2096 ``` 2097 2098 2099### queryMimeType<sup>(deprecated)</sup> 2100 2101queryMimeType(callback: AsyncCallback<string>): void; 2102 2103Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. 2104 2105> **NOTE** 2106> 2107> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9-1) instead. 2108 2109**Required permissions**: ohos.permission.INTERNET 2110 2111**System capability**: SystemCapability.MiscServices.Download 2112 2113**Parameters** 2114 2115| Name| Type| Mandatory| Description| 2116| -------- | -------- | -------- | -------- | 2117| 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.| 2118 2119**Error codes** 2120 2121For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2122 2123| ID| Error Message| 2124| -------- | -------- | 2125| 201 | the permissions check fails | 2126 2127**Example** 2128 2129 ```js 2130 downloadTask.queryMimeType((err, data)=>{ 2131 if(err) { 2132 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 2133 } else { 2134 console.info('Succeeded in querying the download mimeType.'); 2135 } 2136 }); 2137 ``` 2138 2139 2140### pause<sup>(deprecated)</sup> 2141 2142pause(): Promise<void> 2143 2144Pauses this download task. This API uses a promise to return the result. 2145 2146> **NOTE** 2147> 2148> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9) instead. 2149 2150**Required permissions**: ohos.permission.INTERNET 2151 2152**System capability**: SystemCapability.MiscServices.Download 2153 2154**Return value** 2155 2156| Type| Description| 2157| -------- | -------- | 2158| Promise<void> | Promise that returns no value.| 2159 2160**Error codes** 2161 2162For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2163 2164| ID| Error Message| 2165| -------- | -------- | 2166| 201 | the permissions check fails | 2167 2168**Example** 2169 2170 ```js 2171 downloadTask.pause().then((result) => { 2172 console.info('Succeeded in pausing the download task.'); 2173 }).catch((err) => { 2174 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 2175 }); 2176 ``` 2177 2178 2179### pause<sup>(deprecated)</sup> 2180 2181pause(callback: AsyncCallback<void>): void 2182 2183> **NOTE** 2184> 2185> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9-1) instead. 2186 2187Pauses this download task. This API uses an asynchronous callback to return the result. 2188 2189**Required permissions**: ohos.permission.INTERNET 2190 2191**System capability**: SystemCapability.MiscServices.Download 2192 2193**Parameters** 2194 2195| Name| Type| Mandatory| Description| 2196| -------- | -------- | -------- | -------- | 2197| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 2198 2199**Error codes** 2200 2201For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2202 2203| ID| Error Message| 2204| -------- | -------- | 2205| 201 | the permissions check fails | 2206 2207**Example** 2208 2209 ```js 2210 downloadTask.pause((err, result)=>{ 2211 if(err) { 2212 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 2213 return; 2214 } 2215 console.info('Succeeded in pausing the download task.'); 2216 }); 2217 ``` 2218 2219 2220### resume<sup>(deprecated)</sup> 2221 2222resume(): Promise<void> 2223 2224Resumes this download task. This API uses a promise to return the result. 2225 2226> **NOTE** 2227> 2228> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9) instead. 2229 2230**Required permissions**: ohos.permission.INTERNET 2231 2232**System capability**: SystemCapability.MiscServices.Download 2233 2234**Return value** 2235 2236| Type| Description| 2237| -------- | -------- | 2238| Promise<void> | Promise that returns no value.| 2239 2240**Error codes** 2241 2242For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2243 2244| ID| Error Message| 2245| -------- | -------- | 2246| 201 | the permissions check fails | 2247 2248**Example** 2249 2250 ```js 2251 downloadTask.resume().then((result) => { 2252 console.info('Succeeded in resuming the download task.') 2253 }).catch((err) => { 2254 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 2255 }); 2256 ``` 2257 2258 2259### resume<sup>(deprecated)</sup> 2260 2261resume(callback: AsyncCallback<void>): void 2262 2263> **NOTE** 2264> 2265> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9-1) instead. 2266 2267Resumes this download task. This API uses an asynchronous callback to return the result. 2268 2269**Required permissions**: ohos.permission.INTERNET 2270 2271**System capability**: SystemCapability.MiscServices.Download 2272 2273**Parameters** 2274 2275| Name| Type| Mandatory| Description| 2276| -------- | -------- | -------- | -------- | 2277| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 2278 2279**Error codes** 2280 2281For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2282 2283| ID| Error Message| 2284| -------- | -------- | 2285| 201 | the permissions check fails | 2286 2287**Example** 2288 2289 ```js 2290 downloadTask.resume((err, result)=>{ 2291 if (err) { 2292 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 2293 return; 2294 } 2295 console.info('Succeeded in resuming the download task.'); 2296 }); 2297 ``` 2298 2299 2300## DownloadConfig 2301Defines the download task configuration. 2302 2303**System capability**: SystemCapability.MiscServices.Download 2304 2305| Name| Type| Mandatory| Description| 2306| -------- | -------- | -------- | -------- | 2307| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.| 2308| header | Object | No| HTTPS flag header to be included in the download request.| 2309| enableMetered | boolean | No| Whether download is allowed on a metered connection. The default value is **false**. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.<br>- **true**: allowed<br>- **false**: not allowed| 2310| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.<br>- **true**: allowed<br>- **false**: not allowed| 2311| description | string | No| Description of the download session.| 2312| filePath<sup>7+</sup> | 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.<br>- In the FA model, use [context](../apis-ability-kit/js-apis-inner-app-context.md#contextgetcachedir) to obtain the application storage path.<br>- In the stage model, use [AbilityContext](../apis-ability-kit/js-apis-inner-application-context.md) to obtain the application storage path.| 2313| networkType | number | No| Network type allowed for the download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.<br>- NETWORK_MOBILE: 0x00000001<br>- NETWORK_WIFI: 0x00010000| 2314| title | string | No| Download task name.| 2315| background<sup>9+</sup> | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| 2316 2317 2318## DownloadInfo<sup>7+</sup> 2319Defines the download task information, which is the callback parameter of the [getTaskInfo<sup>9+</sup>](#gettaskinfo9) API. 2320 2321**System capability**: SystemCapability.MiscServices.Download 2322 2323| Name| Type|Mandatory| Description| 2324| -------- | -------- | -------- | -------- | 2325| downloadId | number |Yes| ID of the download task.| 2326| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#constants).| 2327| fileName | string |Yes| Name of the downloaded file.| 2328| filePath | string |Yes| URI of the saved file.| 2329| pausedReason | number |Yes| Cause of download pause. The value can be any constant in [Causes of Download Pause](#constants).| 2330| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#constants).| 2331| targetURI | string |Yes| URI of the downloaded file.| 2332| downloadTitle | string |Yes| Name of the download task.| 2333| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| 2334| description | string |Yes| Description of the download task.| 2335| downloadedBytes | number |Yes| Real-time download size, in bytes.| 2336 2337## Action<sup>10+</sup> 2338 2339Defines action options. 2340 2341**Atomic service API**: This API can be used in atomic services since API version 11. 2342 2343**System capability**: SystemCapability.Request.FileTransferAgent 2344 2345| Name| Value|Description| 2346| -------- | -------- |-------- | 2347| DOWNLOAD | 0 |Download.| 2348| UPLOAD | 1 |Upload.| 2349 2350 2351## Mode<sup>10+</sup> 2352Defines mode options.<br> 2353After an application is switched to the background for a period of time, background tasks are not affected but foreground tasks will fail or pause. 2354 2355**Atomic service API**: This API can be used in atomic services since API version 11. 2356 2357**System capability**: SystemCapability.Request.FileTransferAgent 2358 2359| Name| Value|Description| 2360| -------- | -------- |-------- | 2361| BACKGROUND | 0 |Background task.| 2362| FOREGROUND | 1 |Foreground task.| 2363 2364## Network<sup>10+</sup> 2365 2366Defines network options.<br> 2367If 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. 2368 2369**Atomic service API**: This API can be used in atomic services since API version 11. 2370 2371**System capability**: SystemCapability.Request.FileTransferAgent 2372 2373| Name| Value|Description| 2374| -------- | -------- |-------- | 2375| ANY | 0 |Network of any type.| 2376| WIFI | 1 |Wi-Fi network.| 2377| CELLULAR | 2 |Cellular data network.| 2378 2379## BroadcastEvent<sup>11+</sup> 2380 2381Defines a custom system event. You can use a common event API to obtain the event. 2382The 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. 2383 2384You can use the **CommonEventData** type to transmit data related to common events. The members in **CommonEventData** are different from those described in [CommonEventData](js-apis-inner-commonEvent-commonEventData.md). Specifically, **CommonEventData.code** indicates the task status, which is **0x40 COMPLETE** or **0x41 FAILED**, and **CommonEventData.data** indicates the task ID. 2385 2386<!--Del--> 2387For details about event configuration information, see [Subscribing to Common Events in Static Mode (for System Applications Only)](../../basic-services/common-event/common-event-static-subscription.md).<!--DelEnd--> 2388 2389**System capability**: SystemCapability.Request.FileTransferAgent 2390 2391| Name| Value| Description | 2392| -------- | ------- |-----------| 2393| COMPLETE | 'ohos.request.event.COMPLETE' | Task completion event.| 2394 2395## FileSpec<sup>10+</sup> 2396Provides the file information of a table item. 2397 2398**Atomic service API**: This API can be used in atomic services since API version 11. 2399 2400**System capability**: SystemCapability.Request.FileTransferAgent 2401 2402| Name| Type| Mandatory| Description| 2403| -------- | -------- | -------- | -------- | 2404| path | string | Yes| File path:<br>- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.<br>- 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**.<br>- Application sandbox directory. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.<br>- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>- User public file, for example, **file://media/Photo/path/to/file.img**. Only frontend tasks are supported.| 2405| mimeType | string | No| MIME type of the file, which is obtained from the file name.| 2406| filename | string | No| File name. The default value is obtained from the file path.| 2407| extras | object | No| Additional information. This parameter is not included in HTTP requests.| 2408 2409 2410## FormItem<sup>10+</sup> 2411Describes the form item of a task. 2412 2413**Atomic service API**: This API can be used in atomic services since API version 11. 2414 2415**System capability**: SystemCapability.Request.FileTransferAgent 2416 2417| Name| Type| Mandatory| Description| 2418| -------- | -------- | -------- | -------- | 2419| name | string | Yes| Form parameter name.| 2420| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes| Form parameter value.| 2421 2422 2423## Config<sup>10+</sup> 2424Provides the configuration information of an upload or download task. 2425 2426**System capability**: SystemCapability.Request.FileTransferAgent 2427 2428| Name| Type| Mandatory| Description| 2429| -------- | -------- | -------- | -------- | 2430| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2431| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2432| 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**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2433| description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2434| mode | [Mode](#mode10) | No| Task mode. The default mode is background.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2435| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.<br>- **true**: Overwrite the existing file.<br>- **false**: Do not overwrite the existing file. In this case, the download fails.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2436| method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.<br>- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.<br>- If the task is a download, use **GET** or **POST**. The default value is **GET**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2437| headers | object | No| HTTP headers to be included in the task.<br>- If the task is an upload, the default **Content-Type** is **multipart/form-data**.<br>- If the task is a download, the default **Content-Type** is **application/json**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2438| data | string \| Array<[FormItem](#formitem10)> | No| Task data.<br>- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.<br>- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2439| saveas | string | No| Path for storing downloaded files. The options are as follows:<br>- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.<br>- 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**.<br>- Application sandbox directory. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.<br>- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>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.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2440| network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2441| metered | boolean | No| Whether the task is allowed on a metered connection. The default value is **false**.<br>- **true**: task allowed on a metered connection.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2442| roaming | boolean | No| Whether the task is allowed on a roaming network. The default value is **true**.<br>- **true**: task allowed on a roaming network.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2443| retry | boolean | No| Whether automatic retry is enabled for the task. This parameter is only applicable to background tasks. The default value is **true**.<br>- **true**: automatic retry is enabled.<br>- **false**: automatic retry is disabled.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2444| redirect | boolean | No| Whether redirection is allowed. The default value is **true**.<br>- **true**: redirection allowed.<br>- **false**: redirection not allowed.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2445| proxy<sup>12+</sup> | string | No| Proxy address. The value contains a maximum of 512 characters.<br>It is in the format of http://\<domain or address\>:\<port\>. By default, this parameter is left blank.| 2446| index | number | No| Path index of the task. It is usually used for resumable downloads. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2447| begins | number | No| File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the beginning of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2448| ends | number | No| File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the end of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2449| gauge | boolean | No| Whether to send progress notifications. This parameter applies only to background tasks. The default value is **false**.<br>- **false**: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.<br>- **true**: Progress notifications are sent to indicate the result of each file.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2450| precise | boolean | No| - If this parameter is set to **true**, the task fails when the file size cannot be obtained.<br>- If this parameter is set to **false**, the task continues when the file size is set to **-1**.<br>The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2451| token | string | No| Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2452| priority<sup>11+</sup> | number | No| Priority of the task. For tasks in the same mode, a smaller value indicates a higher priority.<br>Default value: **0**| 2453| extras | object | No| Additional information of the task. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2454 2455## State<sup>10+</sup> 2456 2457Defines the current task status. 2458 2459**Atomic service API**: This API can be used in atomic services since API version 11. 2460 2461**System capability**: SystemCapability.Request.FileTransferAgent 2462 2463| Name| Value|Description| 2464| -------- | -------- |-------- | 2465| INITIALIZED | 0x00 |The task is initialized based on the configuration specified in [Config](#config10).| 2466| WAITING | 0x10 |The task lacks resources for running or the resources for retries do not match the network status.| 2467| RUNNING | 0x20 |The task is being executed.| 2468| RETRYING | 0x21 |The task has failed at least once and is being executed again.| 2469| PAUSED | 0x30 |The task is suspended and will be resumed later.| 2470| STOPPED | 0x31 |The task is stopped.| 2471| COMPLETED | 0x40 |The task is complete.| 2472| FAILED | 0x41 |The task fails.| 2473| REMOVED | 0x50 |The task is removed.| 2474 2475 2476## Progress<sup>10+</sup> 2477Describes the data structure of the task progress. 2478 2479**Atomic service API**: This API can be used in atomic services since API version 11. 2480 2481**System capability**: SystemCapability.Request.FileTransferAgent 2482 2483| Name| Type| Mandatory| Description | 2484| -------- | -------- | -------- |---------------------------------------------------------------------| 2485| state | [State](#state10) | Yes| Current task status. | 2486| index | number | Yes| Index of the file that is being processed in the task. | 2487| processed | number | Yes| Size of processed data in the current file in the task, in bytes. | 2488| 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**.| 2489| extras | object | No| Extra information of the task, for example, the header and body of the response from the server. | 2490 2491 2492## Faults<sup>10+</sup> 2493 2494Defines the cause of a task failure. 2495 2496**Atomic service API**: This API can be used in atomic services since API version 11. 2497 2498**System capability**: SystemCapability.Request.FileTransferAgent 2499 2500| Name| Value| Description | 2501| -------- | -------- |--------------------------------------------------------------------------------| 2502| OTHERS | 0xFF | Other fault. | 2503| DISCONNECTED | 0x00 | Network disconnection. | 2504| TIMEOUT | 0x10 | Timeout. | 2505| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | 2506| PARAM<sup>12+</sup> | 0x30 | Parameter error, for example, incorrect URL format.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2507| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | 2508| DNS<sup>12+</sup> | 0x50 | DNS resolution error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2509| TCP<sup>12+</sup> | 0x60 | TCP connection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2510| SSL<sup>12+</sup> | 0x70 | SSL connection error, for example, a certificate error or certificate verification failure.<br>**Atomic service API**: This API can be used in atomic services since API version 12.| 2511| REDIRECT<sup>12+</sup> | 0x80 | Redirection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2512 2513> **NOTE** 2514> 2515> 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. 2516 2517## Filter<sup>10+</sup> 2518Defines the filter criteria. 2519 2520**System capability**: SystemCapability.Request.FileTransferAgent 2521 2522| Name| Type| Mandatory| Description| 2523| -------- | -------- | -------- | -------- | 2524| before | number | No| Unix timestamp of the end time, in milliseconds. The default value is the invoking time.| 2525| after | number | No| Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours.| 2526| state | [State](#state10) | No| Task state.| 2527| action | [Action](#action10) | No| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2528| mode | [Mode](#mode10) | No| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.<br>- No value: All tasks are queried.| 2529 2530## TaskInfo<sup>10+</sup> 2531Defines the data structure of the task information for query. The fields available vary depending on the query type. 2532 2533**System capability**: SystemCapability.Request.FileTransferAgent 2534 2535| Name| Type| Mandatory| Description| 2536| -------- | -------- | -------- | -------- | 2537| saveas | string | No| Path for storing downloaded files.| 2538| url | string | No| Task URL.<br>It can be obtained through [request.agent.show<sup>10+</sup>](#requestagentshow10-1) or [request.agent.touch<sup>10+</sup>](#requestagenttouch10-1).| 2539| data | string \| Array<[FormItem](#formitem10)> | No| Task value.<br>It can be obtained through [request.agent.show<sup>10+</sup>](#requestagentshow10-1) or [request.agent.touch<sup>10+</sup>](#requestagenttouch10-1).| 2540| tid | string | Yes| Task ID.| 2541| title | string | Yes| Task title.| 2542| description | string | Yes| Task description.| 2543| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2544| mode | [Mode](#mode10) | Yes| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.| 2545| priority<sup>11+</sup> | 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.| 2546| mimeType | string | Yes| MIME type in the task configuration.| 2547| progress | [Progress](#progress10) | Yes| Task progress.| 2548| gauge | boolean | Yes| Whether to send progress notifications. This parameter applies only to background tasks.| 2549| ctime | number | Yes | Unix timestamp when the task is created, in milliseconds. The value is generated by the system of the current device.<br/>**NOTE**<br>When [request.agent.search<sup>10+</sup>](#requestagentsearch10-1) 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](#filter10). | 2550| mtime | number | Yes| Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device.| 2551| retry | boolean | Yes| Whether automatic retry is enabled for the task. This parameter applies only to background tasks.| 2552| tries | number | Yes| Number of retries of the task.| 2553| faults | [Faults](#faults10) | Yes| Failure cause of the task.| 2554| reason | string | Yes| Reason why the task is waiting, failed, stopped, or paused.| 2555| extras | object | No| Extra information of the task.| 2556 2557 2558## HttpResponse<sup>12+</sup> 2559Data structure of the task response header. 2560 2561**Atomic service API**: This API can be used in atomic services since API version 12. 2562 2563**System capability**: SystemCapability.Request.FileTransferAgent 2564 2565| Name| Type| Mandatory| Description| 2566| -------- | -------- | -------- | -------- | 2567| version | string | Yes| HTTP version.| 2568| statusCode | number | Yes| HTTP response status code.| 2569| reason | string | Yes| HTTP response cause.| 2570| headers | Map<string, Array<string>> | Yes| HTTP response header.| 2571 2572## Task<sup>10+</sup> 2573Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create<sup>10+</sup>](#requestagentcreate10-1) or from a callback through [request.agent.create<sup>10+</sup>](#requestagentcreate10). 2574 2575### Attributes 2576Task attributes include the task ID and task configuration. 2577 2578**Atomic service API**: This API can be used in atomic services since API version 11. 2579 2580**System capability**: SystemCapability.Request.FileTransferAgent 2581 2582| Name| Type| Mandatory| Description| 2583| -------- | -------- | -------- | -------- | 2584| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.| 2585| config | [Config](#config10) | Yes| Task configuration.| 2586 2587> **NOTE** 2588> 2589> The **Task** object and its mounting callback function are released and automatically reclaimed by the system after the **remove** method is called. 2590 2591### on('progress')<sup>10+</sup> 2592 2593on(event: 'progress', callback: (progress: [Progress](#progress10)) => void): void 2594 2595Subscribes to task progress changes. This API uses an asynchronous callback to return the result. 2596 2597**Atomic service API**: This API can be used in atomic services since API version 11. 2598 2599**System capability**: SystemCapability.Request.FileTransferAgent 2600 2601**Parameters** 2602 2603| Name| Type| Mandatory| Description| 2604| -------- | -------- | -------- | -------- | 2605| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 2606| callback | function | Yes| Callback used to return the data structure of the task progress.| 2607 2608**Error codes** 2609 2610For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2611 2612| ID| Error Message| 2613| -------- | -------- | 2614| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2615 2616**Example** 2617 2618 ```ts 2619 import { BusinessError } from '@kit.BasicServicesKit'; 2620 2621 let attachments: Array<request.agent.FormItem> = [{ 2622 name: "taskOnTest", 2623 value: { 2624 filename: "taskOnTest.avi", 2625 mimeType: "application/octet-stream", 2626 path: "./taskOnTest.avi", 2627 } 2628 }]; 2629 let config: request.agent.Config = { 2630 action: request.agent.Action.UPLOAD, 2631 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2632 title: 'taskOnTest', 2633 description: 'Sample code for event listening', 2634 mode: request.agent.Mode.FOREGROUND, 2635 overwrite: false, 2636 method: "PUT", 2637 data: attachments, 2638 saveas: "./", 2639 network: request.agent.Network.CELLULAR, 2640 metered: false, 2641 roaming: true, 2642 retry: true, 2643 redirect: true, 2644 index: 0, 2645 begins: 0, 2646 ends: -1, 2647 gauge: false, 2648 precise: false, 2649 token: "it is a secret" 2650 }; 2651 let createOnCallback = (progress: request.agent.Progress) => { 2652 console.info('upload task progress.'); 2653 }; 2654 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2655 task.on('progress', createOnCallback); 2656 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2657 task.start(); 2658 }).catch((err: BusinessError) => { 2659 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2660 }); 2661 ``` 2662 2663> **NOTE** 2664> 2665> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 2666 2667### on('completed')<sup>10+</sup> 2668 2669on(event: 'completed', callback: (progress: [Progress](#progress10)) => void): void 2670 2671Subscribes to task completion events. This API uses an asynchronous callback to return the result. 2672 2673**Atomic service API**: This API can be used in atomic services since API version 11. 2674 2675**System capability**: SystemCapability.Request.FileTransferAgent 2676 2677**Parameters** 2678 2679| Name| Type| Mandatory| Description| 2680| -------- | -------- | -------- | -------- | 2681| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 2682| callback | function | Yes| Callback used to return the data structure of the task progress.| 2683 2684**Error codes** 2685 2686For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2687 2688| ID| Error Message| 2689| -------- | -------- | 2690| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2691 2692**Example** 2693 2694 ```ts 2695 import { BusinessError } from '@kit.BasicServicesKit'; 2696 2697 let attachments: Array<request.agent.FormItem> = [{ 2698 name: "taskOnTest", 2699 value: { 2700 filename: "taskOnTest.avi", 2701 mimeType: "application/octet-stream", 2702 path: "./taskOnTest.avi", 2703 } 2704 }]; 2705 let config: request.agent.Config = { 2706 action: request.agent.Action.UPLOAD, 2707 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2708 title: 'taskOnTest', 2709 description: 'Sample code for event listening', 2710 mode: request.agent.Mode.FOREGROUND, 2711 overwrite: false, 2712 method: "PUT", 2713 data: attachments, 2714 saveas: "./", 2715 network: request.agent.Network.CELLULAR, 2716 metered: false, 2717 roaming: true, 2718 retry: true, 2719 redirect: true, 2720 index: 0, 2721 begins: 0, 2722 ends: -1, 2723 gauge: false, 2724 precise: false, 2725 token: "it is a secret" 2726 }; 2727 let createOnCallback = (progress: request.agent.Progress) => { 2728 console.info('upload task completed.'); 2729 }; 2730 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2731 task.on('completed', createOnCallback); 2732 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2733 task.start(); 2734 }).catch((err: BusinessError) => { 2735 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2736 }); 2737 ``` 2738 2739> **NOTE** 2740> 2741> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 2742 2743### on('failed')<sup>10+</sup> 2744 2745on(event: 'failed', callback: (progress: [Progress](#progress10)) => void): void 2746 2747Subscribes to task failure events. This API uses an asynchronous callback to return the result. You can call [request.agent.show<sup>10+</sup>](#requestagentshow10-1) to check the error. 2748 2749**Atomic service API**: This API can be used in atomic services since API version 11. 2750 2751**System capability**: SystemCapability.Request.FileTransferAgent 2752 2753**Parameters** 2754 2755| Name| Type| Mandatory| Description| 2756| -------- | -------- | -------- | -------- | 2757| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 2758| callback | function | Yes| Callback used to return the data structure of the task progress.| 2759 2760**Error codes** 2761 2762For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2763 2764| ID| Error Message| 2765| -------- | -------- | 2766| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2767 2768**Example** 2769 2770 ```ts 2771 import { BusinessError } from '@kit.BasicServicesKit'; 2772 2773 let attachments: Array<request.agent.FormItem> = [{ 2774 name: "taskOnTest", 2775 value: { 2776 filename: "taskOnTest.avi", 2777 mimeType: "application/octet-stream", 2778 path: "./taskOnTest.avi", 2779 } 2780 }]; 2781 let config: request.agent.Config = { 2782 action: request.agent.Action.UPLOAD, 2783 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2784 title: 'taskOnTest', 2785 description: 'Sample code for event listening', 2786 mode: request.agent.Mode.FOREGROUND, 2787 overwrite: false, 2788 method: "PUT", 2789 data: attachments, 2790 saveas: "./", 2791 network: request.agent.Network.CELLULAR, 2792 metered: false, 2793 roaming: true, 2794 retry: true, 2795 redirect: true, 2796 index: 0, 2797 begins: 0, 2798 ends: -1, 2799 gauge: false, 2800 precise: false, 2801 token: "it is a secret" 2802 }; 2803 let createOnCallback = (progress: request.agent.Progress) => { 2804 console.info('upload task failed.'); 2805 }; 2806 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2807 task.on('failed', createOnCallback); 2808 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2809 task.start(); 2810 }).catch((err: BusinessError) => { 2811 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2812 }); 2813 ``` 2814 2815> **NOTE** 2816> 2817> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 2818 2819### on('pause')<sup>11+</sup> 2820 2821on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void 2822 2823Subscribes to task pause events. This API uses an asynchronous callback to return the result. 2824 2825**System capability**: SystemCapability.Request.FileTransferAgent 2826 2827**Parameters** 2828 2829| Name| Type| Mandatory| Description| 2830| -------- | -------- | -------- | -------- | 2831| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 2832| callback | function | Yes| Callback used to return the data structure of the task progress.| 2833 2834**Error codes** 2835 2836For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2837 2838| ID| Error Message| 2839| -------- | -------- | 2840| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2841 2842**Example** 2843 2844 ```ts 2845 import { BusinessError } from '@kit.BasicServicesKit'; 2846 2847 let attachments: Array<request.agent.FormItem> = [{ 2848 name: "taskOnTest", 2849 value: { 2850 filename: "taskOnTest.avi", 2851 mimeType: "application/octet-stream", 2852 path: "./taskOnTest.avi", 2853 } 2854 }]; 2855 let config: request.agent.Config = { 2856 action: request.agent.Action.UPLOAD, 2857 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2858 title: 'taskOnTest', 2859 description: 'Sample code for event listening', 2860 mode: request.agent.Mode.FOREGROUND, 2861 overwrite: false, 2862 method: "PUT", 2863 data: attachments, 2864 saveas: "./", 2865 network: request.agent.Network.CELLULAR, 2866 metered: false, 2867 roaming: true, 2868 retry: true, 2869 redirect: true, 2870 index: 0, 2871 begins: 0, 2872 ends: -1, 2873 gauge: false, 2874 precise: false, 2875 token: "it is a secret" 2876 }; 2877 let createOnCallback = (progress: request.agent.Progress) => { 2878 console.info('upload task pause.'); 2879 }; 2880 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2881 task.on('pause', createOnCallback); 2882 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2883 task.start(); 2884 }).catch((err: BusinessError) => { 2885 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2886 }); 2887 ``` 2888 2889> **NOTE** 2890> 2891> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 2892 2893### on('resume')<sup>11+</sup> 2894 2895on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void 2896 2897Subscribes to task resume events. This API uses an asynchronous callback to return the result. 2898 2899**System capability**: SystemCapability.Request.FileTransferAgent 2900 2901**Parameters** 2902 2903| Name| Type| Mandatory| Description| 2904| -------- | -------- | -------- | -------- | 2905| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 2906| callback | function | Yes| Callback used to return the data structure of the task progress.| 2907 2908**Error codes** 2909 2910For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2911 2912| ID| Error Message| 2913| -------- | -------- | 2914| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2915 2916**Example** 2917 2918 ```ts 2919 import { BusinessError } from '@kit.BasicServicesKit'; 2920 2921 let attachments: Array<request.agent.FormItem> = [{ 2922 name: "taskOnTest", 2923 value: { 2924 filename: "taskOnTest.avi", 2925 mimeType: "application/octet-stream", 2926 path: "./taskOnTest.avi", 2927 } 2928 }]; 2929 let config: request.agent.Config = { 2930 action: request.agent.Action.UPLOAD, 2931 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2932 title: 'taskOnTest', 2933 description: 'Sample code for event listening', 2934 mode: request.agent.Mode.FOREGROUND, 2935 overwrite: false, 2936 method: "PUT", 2937 data: attachments, 2938 saveas: "./", 2939 network: request.agent.Network.CELLULAR, 2940 metered: false, 2941 roaming: true, 2942 retry: true, 2943 redirect: true, 2944 index: 0, 2945 begins: 0, 2946 ends: -1, 2947 gauge: false, 2948 precise: false, 2949 token: "it is a secret" 2950 }; 2951 let createOnCallback = (progress: request.agent.Progress) => { 2952 console.info('upload task resume.'); 2953 }; 2954 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2955 task.on('resume', createOnCallback); 2956 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2957 task.start(); 2958 }).catch((err: BusinessError) => { 2959 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2960 }); 2961 ``` 2962 2963> **NOTE** 2964> 2965> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 2966 2967### on('remove')<sup>11+</sup> 2968 2969on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void 2970 2971Subscribes to task removal events. This API uses an asynchronous callback to return the result. 2972 2973**System capability**: SystemCapability.Request.FileTransferAgent 2974 2975**Parameters** 2976 2977| Name| Type| Mandatory| Description| 2978| -------- | -------- | -------- | -------- | 2979| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 2980| callback | function | Yes| Callback used to return the data structure of the task progress.| 2981 2982**Error codes** 2983 2984For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2985 2986| ID| Error Message| 2987| -------- | -------- | 2988| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2989 2990**Example** 2991 2992 ```ts 2993 import { BusinessError } from '@kit.BasicServicesKit'; 2994 2995 let attachments: Array<request.agent.FormItem> = [{ 2996 name: "taskOnTest", 2997 value: { 2998 filename: "taskOnTest.avi", 2999 mimeType: "application/octet-stream", 3000 path: "./taskOnTest.avi", 3001 } 3002 }]; 3003 let config: request.agent.Config = { 3004 action: request.agent.Action.UPLOAD, 3005 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3006 title: 'taskOnTest', 3007 description: 'Sample code for event listening', 3008 mode: request.agent.Mode.FOREGROUND, 3009 overwrite: false, 3010 method: "PUT", 3011 data: attachments, 3012 saveas: "./", 3013 network: request.agent.Network.CELLULAR, 3014 metered: false, 3015 roaming: true, 3016 retry: true, 3017 redirect: true, 3018 index: 0, 3019 begins: 0, 3020 ends: -1, 3021 gauge: false, 3022 precise: false, 3023 token: "it is a secret" 3024 }; 3025 let createOnCallback = (progress: request.agent.Progress) => { 3026 console.info('upload task remove.'); 3027 }; 3028 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3029 task.on('remove', createOnCallback); 3030 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3031 task.start(); 3032 }).catch((err: BusinessError) => { 3033 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3034 }); 3035 ``` 3036 3037> **NOTE** 3038> 3039> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3040 3041### on('response')<sup>12+</sup> 3042 3043on(event: 'response', callback: Callback<HttpResponse>): void 3044 3045Subscribes to task response headers. This API uses an asynchronous callback to return the result. 3046 3047**Atomic service API**: This API can be used in atomic services since API version 12. 3048 3049**System capability**: SystemCapability.Request.FileTransferAgent 3050 3051**Parameters** 3052 3053| Name| Type| Mandatory| Description| 3054| -------- | -------- | -------- | -------- | 3055| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3056| callback | function | Yes| Callback used to return the data structure of the task response header.| 3057 3058**Error codes** 3059 3060For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3061 3062| ID| Error Message| 3063| -------- | -------- | 3064| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3065 3066**Example** 3067 3068 ```ts 3069 import { BusinessError } from '@kit.BasicServicesKit'; 3070 3071 let attachments: Array<request.agent.FormItem> = [{ 3072 name: "taskOnTest", 3073 value: { 3074 filename: "taskOnTest.avi", 3075 mimeType: "application/octet-stream", 3076 path: "./taskOnTest.avi", 3077 } 3078 }]; 3079 let config: request.agent.Config = { 3080 action: request.agent.Action.UPLOAD, 3081 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3082 title: 'taskOnTest', 3083 description: 'Sample code for event listening', 3084 mode: request.agent.Mode.FOREGROUND, 3085 overwrite: false, 3086 method: "PUT", 3087 data: attachments, 3088 saveas: "./", 3089 network: request.agent.Network.CELLULAR, 3090 metered: false, 3091 roaming: true, 3092 retry: true, 3093 redirect: true, 3094 index: 0, 3095 begins: 0, 3096 ends: -1, 3097 gauge: false, 3098 precise: false, 3099 token: "it is a secret" 3100 }; 3101 let createOnCallback = (response: request.agent.HttpResponse) => { 3102 console.info('upload task response.'); 3103 }; 3104 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3105 task.on('response', createOnCallback); 3106 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3107 task.start(); 3108 }).catch((err: BusinessError) => { 3109 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3110 }); 3111 ``` 3112 3113> **NOTE** 3114> 3115> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3116 3117### off('progress')<sup>10+</sup> 3118 3119off(event: 'progress', callback?: (progress: [Progress](#progress10)) => void): void 3120 3121Unsubscribes from task progress events. 3122 3123**Atomic service API**: This API can be used in atomic services since API version 11. 3124 3125**System capability**: SystemCapability.Request.FileTransferAgent 3126 3127**Parameters** 3128 3129| Name| Type| Mandatory| Description| 3130| -------- | -------- | -------- | -------- | 3131| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 3132| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3133 3134**Error codes** 3135 3136For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3137 3138| ID| Error Message| 3139| -------- | -------- | 3140| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3141 3142**Example** 3143 3144 ```ts 3145 import { BusinessError } from '@kit.BasicServicesKit'; 3146 3147 let attachments: Array<request.agent.FormItem> = [{ 3148 name: "taskOffTest", 3149 value: { 3150 filename: "taskOffTest.avi", 3151 mimeType: "application/octet-stream", 3152 path: "./taskOffTest.avi", 3153 } 3154 }]; 3155 let config: request.agent.Config = { 3156 action: request.agent.Action.UPLOAD, 3157 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3158 title: 'taskOffTest', 3159 description: 'Sample code for event listening', 3160 mode: request.agent.Mode.FOREGROUND, 3161 overwrite: false, 3162 method: "PUT", 3163 data: attachments, 3164 saveas: "./", 3165 network: request.agent.Network.CELLULAR, 3166 metered: false, 3167 roaming: true, 3168 retry: true, 3169 redirect: true, 3170 index: 0, 3171 begins: 0, 3172 ends: -1, 3173 gauge: false, 3174 precise: false, 3175 token: "it is a secret" 3176 }; 3177 let createOffCallback1 = (progress: request.agent.Progress) => { 3178 console.info('upload task progress.'); 3179 }; 3180 let createOffCallback2 = (progress: request.agent.Progress) => { 3181 console.info('upload task progress.'); 3182 }; 3183 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3184 task.on('progress', createOffCallback1); 3185 task.on('progress', createOffCallback2); 3186 // Unsubscribe from createOffCallback1. 3187 task.off('progress', createOffCallback1); 3188 // Unsubscribe from all callbacks of task progress changes. 3189 task.off('progress'); 3190 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3191 task.start(); 3192 }).catch((err: BusinessError) => { 3193 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3194 }); 3195 ``` 3196 3197> **NOTE** 3198> 3199> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3200 3201### off('completed')<sup>10+</sup> 3202 3203off(event: 'completed', callback?: (progress: [Progress](#progress10)) => void): void 3204 3205Unsubscribes from task completion events. 3206 3207**Atomic service API**: This API can be used in atomic services since API version 11. 3208 3209**System capability**: SystemCapability.Request.FileTransferAgent 3210 3211**Parameters** 3212 3213| Name| Type| Mandatory| Description| 3214| -------- | -------- | -------- | -------- | 3215| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 3216| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3217 3218**Error codes** 3219 3220For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3221 3222| ID| Error Message| 3223| -------- | -------- | 3224| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3225 3226**Example** 3227 3228 ```ts 3229 import { BusinessError } from '@kit.BasicServicesKit'; 3230 3231 let attachments: Array<request.agent.FormItem> = [{ 3232 name: "taskOffTest", 3233 value: { 3234 filename: "taskOffTest.avi", 3235 mimeType: "application/octet-stream", 3236 path: "./taskOffTest.avi", 3237 } 3238 }]; 3239 let config: request.agent.Config = { 3240 action: request.agent.Action.UPLOAD, 3241 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3242 title: 'taskOffTest', 3243 description: 'Sample code for event listening', 3244 mode: request.agent.Mode.FOREGROUND, 3245 overwrite: false, 3246 method: "PUT", 3247 data: attachments, 3248 saveas: "./", 3249 network: request.agent.Network.CELLULAR, 3250 metered: false, 3251 roaming: true, 3252 retry: true, 3253 redirect: true, 3254 index: 0, 3255 begins: 0, 3256 ends: -1, 3257 gauge: false, 3258 precise: false, 3259 token: "it is a secret" 3260 }; 3261 let createOffCallback1 = (progress: request.agent.Progress) => { 3262 console.info('upload task completed.'); 3263 }; 3264 let createOffCallback2 = (progress: request.agent.Progress) => { 3265 console.info('upload task completed.'); 3266 }; 3267 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3268 task.on('completed', createOffCallback1); 3269 task.on('completed', createOffCallback2); 3270 // Unsubscribe from createOffCallback1. 3271 task.off('completed', createOffCallback1); 3272 // Unsubscribe from all callbacks of the task completion events. 3273 task.off('completed'); 3274 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3275 task.start(); 3276 }).catch((err: BusinessError) => { 3277 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3278 }); 3279 ``` 3280 3281> **NOTE** 3282> 3283> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3284 3285### off('failed')<sup>10+</sup> 3286 3287off(event: 'failed', callback?: (progress: [Progress](#progress10)) => void): void 3288 3289Unsubscribes from task failure events. 3290 3291**Atomic service API**: This API can be used in atomic services since API version 11. 3292 3293**System capability**: SystemCapability.Request.FileTransferAgent 3294 3295**Parameters** 3296 3297| Name| Type| Mandatory| Description| 3298| -------- | -------- | -------- | -------- | 3299| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 3300| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3301 3302**Error codes** 3303 3304For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3305 3306| ID| Error Message| 3307| -------- | -------- | 3308| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3309 3310**Example** 3311 3312 ```ts 3313 import { BusinessError } from '@kit.BasicServicesKit'; 3314 3315 let attachments: Array<request.agent.FormItem> = [{ 3316 name: "taskOffTest", 3317 value: { 3318 filename: "taskOffTest.avi", 3319 mimeType: "application/octet-stream", 3320 path: "./taskOffTest.avi", 3321 } 3322 }]; 3323 let config: request.agent.Config = { 3324 action: request.agent.Action.UPLOAD, 3325 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3326 title: 'taskOffTest', 3327 description: 'Sample code for event listening', 3328 mode: request.agent.Mode.FOREGROUND, 3329 overwrite: false, 3330 method: "PUT", 3331 data: attachments, 3332 saveas: "./", 3333 network: request.agent.Network.CELLULAR, 3334 metered: false, 3335 roaming: true, 3336 retry: true, 3337 redirect: true, 3338 index: 0, 3339 begins: 0, 3340 ends: -1, 3341 gauge: false, 3342 precise: false, 3343 token: "it is a secret" 3344 }; 3345 let createOffCallback1 = (progress: request.agent.Progress) => { 3346 console.info('upload task failed.'); 3347 }; 3348 let createOffCallback2 = (progress: request.agent.Progress) => { 3349 console.info('upload task failed.'); 3350 }; 3351 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3352 task.on('failed', createOffCallback1); 3353 task.on('failed', createOffCallback2); 3354 // Unsubscribe from createOffCallback1. 3355 task.off('failed', createOffCallback1); 3356 // Unsubscribe from all callbacks of the task failure events. 3357 task.off('failed'); 3358 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3359 task.start(); 3360 }).catch((err: BusinessError) => { 3361 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3362 }); 3363 ``` 3364 3365> **NOTE** 3366> 3367> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3368 3369### off('pause')<sup>11+</sup> 3370 3371off(event: 'pause', callback?: (progress: [Progress](#progress10)) => void): void 3372 3373Unsubscribes from the foreground task pause event. 3374 3375**System capability**: SystemCapability.Request.FileTransferAgent 3376 3377**Parameters** 3378 3379| Name| Type| Mandatory| Description| 3380| -------- | -------- | -------- | -------- | 3381| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 3382| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3383 3384**Error codes** 3385 3386For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3387 3388| ID| Error Message| 3389| -------- | -------- | 3390| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3391 3392**Example** 3393 3394 ```ts 3395 import { BusinessError } from '@kit.BasicServicesKit'; 3396 3397 let attachments: Array<request.agent.FormItem> = [{ 3398 name: "taskOffTest", 3399 value: { 3400 filename: "taskOffTest.avi", 3401 mimeType: "application/octet-stream", 3402 path: "./taskOffTest.avi", 3403 } 3404 }]; 3405 let config: request.agent.Config = { 3406 action: request.agent.Action.UPLOAD, 3407 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3408 title: 'taskOffTest', 3409 description: 'Sample code for event listening', 3410 mode: request.agent.Mode.FOREGROUND, 3411 overwrite: false, 3412 method: "PUT", 3413 data: attachments, 3414 saveas: "./", 3415 network: request.agent.Network.CELLULAR, 3416 metered: false, 3417 roaming: true, 3418 retry: true, 3419 redirect: true, 3420 index: 0, 3421 begins: 0, 3422 ends: -1, 3423 gauge: false, 3424 precise: false, 3425 token: "it is a secret" 3426 }; 3427 let createOffCallback1 = (progress: request.agent.Progress) => { 3428 console.info('upload task pause.'); 3429 }; 3430 let createOffCallback2 = (progress: request.agent.Progress) => { 3431 console.info('upload task pause.'); 3432 }; 3433 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3434 task.on('pause', createOffCallback1); 3435 task.on('pause', createOffCallback2); 3436 // Unsubscribe from createOffCallback1. 3437 task.off('pause', createOffCallback1); 3438 // Unsubscribe from all callbacks of the foreground task pause event. 3439 task.off('pause'); 3440 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3441 task.start(); 3442 }).catch((err: BusinessError) => { 3443 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3444 }); 3445 ``` 3446 3447> **NOTE** 3448> 3449> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3450 3451### off('resume')<sup>11+</sup> 3452 3453off(event: 'resume', callback?: (progress: [Progress](#progress10)) => void): void 3454 3455Unsubscribes from the foreground task resume event. 3456 3457**System capability**: SystemCapability.Request.FileTransferAgent 3458 3459**Parameters** 3460 3461| Name| Type| Mandatory| Description| 3462| -------- | -------- | -------- | -------- | 3463| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 3464| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3465 3466**Error codes** 3467 3468For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3469 3470| ID| Error Message| 3471| -------- | -------- | 3472| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3473 3474**Example** 3475 3476 ```ts 3477 import { BusinessError } from '@kit.BasicServicesKit'; 3478 3479 let attachments: Array<request.agent.FormItem> = [{ 3480 name: "taskOffTest", 3481 value: { 3482 filename: "taskOffTest.avi", 3483 mimeType: "application/octet-stream", 3484 path: "./taskOffTest.avi", 3485 } 3486 }]; 3487 let config: request.agent.Config = { 3488 action: request.agent.Action.UPLOAD, 3489 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3490 title: 'taskOffTest', 3491 description: 'Sample code for event listening', 3492 mode: request.agent.Mode.FOREGROUND, 3493 overwrite: false, 3494 method: "PUT", 3495 data: attachments, 3496 saveas: "./", 3497 network: request.agent.Network.CELLULAR, 3498 metered: false, 3499 roaming: true, 3500 retry: true, 3501 redirect: true, 3502 index: 0, 3503 begins: 0, 3504 ends: -1, 3505 gauge: false, 3506 precise: false, 3507 token: "it is a secret" 3508 }; 3509 let createOffCallback1 = (progress: request.agent.Progress) => { 3510 console.info('upload task resume.'); 3511 }; 3512 let createOffCallback2 = (progress: request.agent.Progress) => { 3513 console.info('upload task resume.'); 3514 }; 3515 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3516 task.on('resume', createOffCallback1); 3517 task.on('resume', createOffCallback2); 3518 // Unsubscribe from createOffCallback1. 3519 task.off('resume', createOffCallback1); 3520 // Unsubscribe from all callbacks of the foreground task resume event. 3521 task.off('resume'); 3522 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3523 task.start(); 3524 }).catch((err: BusinessError) => { 3525 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3526 }); 3527 ``` 3528 3529> **NOTE** 3530> 3531> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3532 3533### off('remove')<sup>11+</sup> 3534 3535off(event: 'remove', callback?: (progress: [Progress](#progress10)) => void): void 3536 3537Unsubscribes from the task removal event. 3538 3539**System capability**: SystemCapability.Request.FileTransferAgent 3540 3541**Parameters** 3542 3543| Name| Type| Mandatory| Description| 3544| -------- | -------- | -------- | -------- | 3545| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 3546| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3547 3548**Error codes** 3549 3550For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3551 3552| ID| Error Message| 3553| -------- | -------- | 3554| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3555 3556**Example** 3557 3558 ```ts 3559 import { BusinessError } from '@kit.BasicServicesKit'; 3560 3561 let attachments: Array<request.agent.FormItem> = [{ 3562 name: "taskOffTest", 3563 value: { 3564 filename: "taskOffTest.avi", 3565 mimeType: "application/octet-stream", 3566 path: "./taskOffTest.avi", 3567 } 3568 }]; 3569 let config: request.agent.Config = { 3570 action: request.agent.Action.UPLOAD, 3571 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3572 title: 'taskOffTest', 3573 description: 'Sample code for event listening', 3574 mode: request.agent.Mode.FOREGROUND, 3575 overwrite: false, 3576 method: "PUT", 3577 data: attachments, 3578 saveas: "./", 3579 network: request.agent.Network.CELLULAR, 3580 metered: false, 3581 roaming: true, 3582 retry: true, 3583 redirect: true, 3584 index: 0, 3585 begins: 0, 3586 ends: -1, 3587 gauge: false, 3588 precise: false, 3589 token: "it is a secret" 3590 }; 3591 let createOffCallback1 = (progress: request.agent.Progress) => { 3592 console.info('upload task remove.'); 3593 }; 3594 let createOffCallback2 = (progress: request.agent.Progress) => { 3595 console.info('upload task remove.'); 3596 }; 3597 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3598 task.on('remove', createOffCallback1); 3599 task.on('remove', createOffCallback2); 3600 // Unsubscribe from createOffCallback1. 3601 task.off('remove', createOffCallback1); 3602 // Unsubscribe from all callbacks of the task removal event. 3603 task.off('remove'); 3604 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3605 task.start(); 3606 }).catch((err: BusinessError) => { 3607 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3608 }); 3609 ``` 3610 3611> **NOTE** 3612> 3613> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3614 3615### off('response')<sup>12+</sup> 3616 3617off(event: 'response', callback?: Callback<HttpResponse>): void 3618 3619Unsubscribes from task response headers. 3620 3621**Atomic service API**: This API can be used in atomic services since API version 12. 3622 3623**System capability**: SystemCapability.Request.FileTransferAgent 3624 3625**Parameters** 3626 3627| Name| Type| Mandatory| Description| 3628| -------- | -------- | -------- | -------- | 3629| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3630| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3631 3632**Error codes** 3633 3634For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3635 3636| ID| Error Message| 3637| -------- | -------- | 3638| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3639 3640**Example** 3641 3642 ```ts 3643 import { BusinessError } from '@kit.BasicServicesKit'; 3644 3645 let attachments: Array<request.agent.FormItem> = [{ 3646 name: "taskOffTest", 3647 value: { 3648 filename: "taskOffTest.avi", 3649 mimeType: "application/octet-stream", 3650 path: "./taskOffTest.avi", 3651 } 3652 }]; 3653 let config: request.agent.Config = { 3654 action: request.agent.Action.UPLOAD, 3655 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3656 title: 'taskOffTest', 3657 description: 'Sample code for event listening', 3658 mode: request.agent.Mode.FOREGROUND, 3659 overwrite: false, 3660 method: "PUT", 3661 data: attachments, 3662 saveas: "./", 3663 network: request.agent.Network.CELLULAR, 3664 metered: false, 3665 roaming: true, 3666 retry: true, 3667 redirect: true, 3668 index: 0, 3669 begins: 0, 3670 ends: -1, 3671 gauge: false, 3672 precise: false, 3673 token: "it is a secret" 3674 }; 3675 let createOffCallback1 = (progress: request.agent.HttpResponse) => { 3676 console.info('upload task response.'); 3677 }; 3678 let createOffCallback2 = (progress: request.agent.HttpResponse) => { 3679 console.info('upload task response.'); 3680 }; 3681 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3682 task.on('response', createOffCallback1); 3683 task.on('response', createOffCallback2); 3684 // Unsubscribe from createOffCallback1. 3685 task.off('response', createOffCallback1); 3686 // Unsubscribe from all callbacks of the task removal event. 3687 task.off('response'); 3688 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3689 task.start(); 3690 }).catch((err: BusinessError) => { 3691 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3692 }); 3693 ``` 3694 3695> **NOTE** 3696> 3697> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3698 3699### start<sup>10+</sup> 3700 3701start(callback: AsyncCallback<void>): void 3702 3703Tasks in the following states can be started: 37041. Task created by **request.agent.create**. 37052. Download tasks that are created by **request.agent.create** but have failed or paused. 3706 3707**Required permissions**: ohos.permission.INTERNET 3708 3709**Atomic service API**: This API can be used in atomic services since API version 11. 3710 3711**System capability**: SystemCapability.Request.FileTransferAgent 3712 3713**Parameters** 3714 3715| Name| Type| Mandatory| Description| 3716| -------- | -------- | -------- | -------- | 3717| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3718 3719**Error codes** 3720 3721For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3722 3723| ID| Error Message| 3724| -------- | -------- | 3725| 201 | Permission denied. | 3726| 13400003 | task service ability error. | 3727| 21900007 | task state error. | 3728 3729**Example** 3730 3731 ```ts 3732 import { BusinessError } from '@kit.BasicServicesKit'; 3733 3734 let config: request.agent.Config = { 3735 action: request.agent.Action.DOWNLOAD, 3736 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3737 title: 'taskStartTest', 3738 description: 'Sample code for start the download task', 3739 mode: request.agent.Mode.BACKGROUND, 3740 overwrite: false, 3741 method: "GET", 3742 data: "", 3743 saveas: "./", 3744 network: request.agent.Network.CELLULAR, 3745 metered: false, 3746 roaming: true, 3747 retry: true, 3748 redirect: true, 3749 index: 0, 3750 begins: 0, 3751 ends: -1, 3752 gauge: false, 3753 precise: false, 3754 token: "it is a secret" 3755 }; 3756 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3757 task.start((err: BusinessError) => { 3758 if (err) { 3759 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3760 return; 3761 } 3762 console.info(`Succeeded in starting a download task.`); 3763 }); 3764 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3765 }).catch((err: BusinessError) => { 3766 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3767 }); 3768 ``` 3769 3770> **NOTE** 3771> 3772> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3773 3774### start<sup>10+</sup> 3775 3776start(): Promise<void> 3777 3778Tasks in the following states can be started: 37791. Task created by **request.agent.create**. 37802. Download tasks that are created by **request.agent.create** but have failed or paused. 3781 3782**Required permissions**: ohos.permission.INTERNET 3783 3784**Atomic service API**: This API can be used in atomic services since API version 11. 3785 3786**System capability**: SystemCapability.Request.FileTransferAgent 3787 3788**Return value** 3789 3790| Type | Description | 3791| ------------------- | ------------------------- | 3792| Promise<void> | Promise that returns no value.| 3793 3794**Error codes** 3795 3796For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3797 3798| ID| Error Message| 3799| -------- | -------- | 3800| 201 | Permission denied. | 3801| 13400003 | task service ability error. | 3802| 21900007 | task state error. | 3803 3804**Example** 3805 3806 ```ts 3807 import { BusinessError } from '@kit.BasicServicesKit'; 3808 3809 let config: request.agent.Config = { 3810 action: request.agent.Action.DOWNLOAD, 3811 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3812 title: 'taskStartTest', 3813 description: 'Sample code for start the download task', 3814 mode: request.agent.Mode.BACKGROUND, 3815 overwrite: false, 3816 method: "GET", 3817 data: "", 3818 saveas: "./", 3819 network: request.agent.Network.CELLULAR, 3820 metered: false, 3821 roaming: true, 3822 retry: true, 3823 redirect: true, 3824 index: 0, 3825 begins: 0, 3826 ends: -1, 3827 gauge: false, 3828 precise: false, 3829 token: "it is a secret" 3830 }; 3831 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3832 task.start().then(() => { 3833 console.info(`Succeeded in starting a download task.`); 3834 }).catch((err: BusinessError) => { 3835 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3836 }); 3837 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3838 }).catch((err: BusinessError) => { 3839 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3840 }); 3841 ``` 3842 3843> **NOTE** 3844> 3845> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 3846 3847### pause<sup>10+</sup> 3848 3849pause(callback: AsyncCallback<void>): void 3850 3851Pauses a task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result. 3852 3853**System capability**: SystemCapability.Request.FileTransferAgent 3854 3855**Parameters** 3856 3857| Name| Type| Mandatory| Description| 3858| -------- | -------- | -------- | -------- | 3859| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3860 3861**Error codes** 3862 3863For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3864 3865| ID| Error Message| 3866| -------- | -------- | 3867| 13400003 | task service ability error. | 3868| 21900007 | task state error. | 3869 3870**Example** 3871 3872 ```ts 3873 import { BusinessError } from '@kit.BasicServicesKit'; 3874 3875 let config: request.agent.Config = { 3876 action: request.agent.Action.DOWNLOAD, 3877 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3878 title: 'taskPauseTest', 3879 description: 'Sample code for pause the download task', 3880 mode: request.agent.Mode.BACKGROUND, 3881 overwrite: false, 3882 method: "GET", 3883 data: "", 3884 saveas: "./", 3885 network: request.agent.Network.CELLULAR, 3886 metered: false, 3887 roaming: true, 3888 retry: true, 3889 redirect: true, 3890 index: 0, 3891 begins: 0, 3892 ends: -1, 3893 gauge: false, 3894 precise: false, 3895 token: "it is a secret" 3896 }; 3897 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3898 task.start(); 3899 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3900 task.pause((err: BusinessError) => { 3901 if (err) { 3902 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3903 return; 3904 } 3905 console.info(`Succeeded in pausing a download task. `); 3906 }); 3907 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3908 }).catch((err: BusinessError) => { 3909 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3910 }); 3911 ``` 3912 3913### pause<sup>10+</sup> 3914 3915pause(): Promise<void> 3916 3917Pauses a task that is waiting, running, or retrying. This API uses a promise to return the result. 3918 3919**System capability**: SystemCapability.Request.FileTransferAgent 3920 3921**Return value** 3922 3923| Type | Description | 3924| ------------------- | ------------------------- | 3925| Promise<void> | Promise that returns no value.| 3926 3927**Error codes** 3928 3929For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3930 3931| ID| Error Message| 3932| -------- | -------- | 3933| 13400003 | task service ability error. | 3934| 21900007 | task state error. | 3935 3936**Example** 3937 3938 ```ts 3939 import { BusinessError } from '@kit.BasicServicesKit'; 3940 3941 let config: request.agent.Config = { 3942 action: request.agent.Action.DOWNLOAD, 3943 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3944 title: 'taskPauseTest', 3945 description: 'Sample code for pause the download task', 3946 mode: request.agent.Mode.BACKGROUND, 3947 overwrite: false, 3948 method: "GET", 3949 data: "", 3950 saveas: "./", 3951 network: request.agent.Network.CELLULAR, 3952 metered: false, 3953 roaming: true, 3954 retry: true, 3955 redirect: true, 3956 index: 0, 3957 begins: 0, 3958 ends: -1, 3959 gauge: false, 3960 precise: false, 3961 token: "it is a secret" 3962 }; 3963 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3964 task.start(); 3965 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3966 task.pause().then(() => { 3967 console.info(`Succeeded in pausing a download task. `); 3968 }).catch((err: BusinessError) => { 3969 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3970 }); 3971 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3972 }).catch((err: BusinessError) => { 3973 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3974 }); 3975 ``` 3976 3977### resume<sup>10+</sup> 3978 3979resume(callback: AsyncCallback<void>): void 3980 3981Resumes a paused task. This API uses an asynchronous callback to return the result. 3982 3983**Required permissions**: ohos.permission.INTERNET 3984 3985**System capability**: SystemCapability.Request.FileTransferAgent 3986 3987**Parameters** 3988 3989| Name| Type| Mandatory| Description| 3990| -------- | -------- | -------- | -------- | 3991| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3992 3993**Error codes** 3994 3995For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3996 3997| ID| Error Message| 3998| -------- | -------- | 3999| 201 | Permission denied. | 4000| 13400003 | task service ability error. | 4001| 21900007 | task state error. | 4002 4003**Example** 4004 4005 ```ts 4006 import { BusinessError } from '@kit.BasicServicesKit'; 4007 4008 let config: request.agent.Config = { 4009 action: request.agent.Action.DOWNLOAD, 4010 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4011 title: 'taskResumeTest', 4012 description: 'Sample code for resume the download task', 4013 mode: request.agent.Mode.BACKGROUND, 4014 overwrite: false, 4015 method: "GET", 4016 data: "", 4017 saveas: "./", 4018 network: request.agent.Network.CELLULAR, 4019 metered: false, 4020 roaming: true, 4021 retry: true, 4022 redirect: true, 4023 index: 0, 4024 begins: 0, 4025 ends: -1, 4026 gauge: false, 4027 precise: false, 4028 token: "it is a secret" 4029 }; 4030 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4031 task.start(); 4032 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4033 task.pause(); 4034 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4035 task.resume((err: BusinessError) => { 4036 if (err) { 4037 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4038 return; 4039 } 4040 console.info(`Succeeded in resuming a download task. `); 4041 }); 4042 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4043 }).catch((err: BusinessError) => { 4044 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4045 }); 4046 ``` 4047 4048### resume<sup>10+</sup> 4049 4050resume(): Promise<void> 4051 4052Resumes a paused task. This API uses a promise to return the result. 4053 4054**Required permissions**: ohos.permission.INTERNET 4055 4056**System capability**: SystemCapability.Request.FileTransferAgent 4057 4058**Return value** 4059 4060| Type | Description | 4061| ------------------- | ------------------------- | 4062| Promise<void> | Promise that returns no value.| 4063 4064**Error codes** 4065 4066For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4067 4068| ID| Error Message| 4069| -------- | -------- | 4070| 201 | Permission denied. | 4071| 13400003 | task service ability error. | 4072| 21900007 | task state error. | 4073 4074**Example** 4075 4076 ```ts 4077 import { BusinessError } from '@kit.BasicServicesKit'; 4078 4079 let config: request.agent.Config = { 4080 action: request.agent.Action.DOWNLOAD, 4081 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4082 title: 'taskResumeTest', 4083 description: 'Sample code for resume the download task', 4084 mode: request.agent.Mode.BACKGROUND, 4085 overwrite: false, 4086 method: "GET", 4087 data: "", 4088 saveas: "./", 4089 network: request.agent.Network.CELLULAR, 4090 metered: false, 4091 roaming: true, 4092 retry: true, 4093 redirect: true, 4094 index: 0, 4095 begins: 0, 4096 ends: -1, 4097 gauge: false, 4098 precise: false, 4099 token: "it is a secret" 4100 }; 4101 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4102 task.start(); 4103 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4104 task.pause(); 4105 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4106 task.resume().then(() => { 4107 console.info(`Succeeded in resuming a download task. `); 4108 }).catch((err: BusinessError) => { 4109 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4110 }); 4111 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4112 }).catch((err: BusinessError) => { 4113 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4114 }); 4115 ``` 4116 4117### stop<sup>10+</sup> 4118 4119stop(callback: AsyncCallback<void>): void 4120 4121Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result. 4122 4123**Atomic service API**: This API can be used in atomic services since API version 11. 4124 4125**System capability**: SystemCapability.Request.FileTransferAgent 4126 4127**Parameters** 4128 4129| Name| Type| Mandatory| Description| 4130| -------- | -------- | -------- | -------- | 4131| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4132 4133**Error codes** 4134 4135For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4136 4137| ID| Error Message| 4138| -------- | -------- | 4139| 13400003 | task service ability error. | 4140| 21900007 | task state error. | 4141 4142**Example** 4143 4144 ```ts 4145 import { BusinessError } from '@kit.BasicServicesKit'; 4146 4147 let config: request.agent.Config = { 4148 action: request.agent.Action.DOWNLOAD, 4149 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4150 title: 'taskStopTest', 4151 description: 'Sample code for stop the download task', 4152 mode: request.agent.Mode.BACKGROUND, 4153 overwrite: false, 4154 method: "GET", 4155 data: "", 4156 saveas: "./", 4157 network: request.agent.Network.CELLULAR, 4158 metered: false, 4159 roaming: true, 4160 retry: true, 4161 redirect: true, 4162 index: 0, 4163 begins: 0, 4164 ends: -1, 4165 gauge: false, 4166 precise: false, 4167 token: "it is a secret" 4168 }; 4169 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4170 task.start(); 4171 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4172 task.stop((err: BusinessError) => { 4173 if (err) { 4174 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4175 return; 4176 } 4177 console.info(`Succeeded in stopping a download task. `); 4178 }); 4179 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4180 }).catch((err: BusinessError) => { 4181 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4182 }); 4183 ``` 4184 4185 4186### stop<sup>10+</sup> 4187 4188stop(): Promise<void> 4189 4190Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. 4191 4192**Atomic service API**: This API can be used in atomic services since API version 11. 4193 4194**System capability**: SystemCapability.Request.FileTransferAgent 4195 4196**Return value** 4197 4198| Type | Description | 4199| ------------------- | ------------------------- | 4200| Promise<void> | Promise that returns no value.| 4201 4202**Error codes** 4203 4204For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4205 4206| ID| Error Message| 4207| -------- | -------- | 4208| 13400003 | task service ability error. | 4209| 21900007 | task state error. | 4210 4211**Example** 4212 4213 ```ts 4214 import { BusinessError } from '@kit.BasicServicesKit'; 4215 4216 let config: request.agent.Config = { 4217 action: request.agent.Action.DOWNLOAD, 4218 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4219 title: 'taskStopTest', 4220 description: 'Sample code for stop the download task', 4221 mode: request.agent.Mode.BACKGROUND, 4222 overwrite: false, 4223 method: "GET", 4224 data: "", 4225 saveas: "./", 4226 network: request.agent.Network.CELLULAR, 4227 metered: false, 4228 roaming: true, 4229 retry: true, 4230 redirect: true, 4231 index: 0, 4232 begins: 0, 4233 ends: -1, 4234 gauge: false, 4235 precise: false, 4236 token: "it is a secret" 4237 }; 4238 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4239 task.start(); 4240 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4241 task.stop().then(() => { 4242 console.info(`Succeeded in stopping a download task. `); 4243 }).catch((err: BusinessError) => { 4244 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4245 }); 4246 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4247 }).catch((err: BusinessError) => { 4248 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4249 }); 4250 ``` 4251 4252## request.agent.create<sup>10+</sup> 4253 4254create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void 4255 4256Creates an upload or download task and adds it to the queue. This API uses an asynchronous callback to return a result. HTTP is supported. 4257 4258 4259**Required permissions**: ohos.permission.INTERNET 4260 4261**Atomic service API**: This API can be used in atomic services since API version 11. 4262 4263**System capability**: SystemCapability.Request.FileTransferAgent 4264 4265**Parameters** 4266 4267| Name| Type| Mandatory| Description| 4268| -------- | -------- | -------- | -------- | 4269| config | [Config](#config10) | Yes| Task configuration.| 4270| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4271| callback | AsyncCallback<[Task](#task10)> | 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.| 4272 4273**Error codes** 4274 4275For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4276 4277| ID| Error Message| 4278| -------- | -------- | 4279| 201 | permission denied. | 4280| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4281| 13400001 | file operation error. | 4282| 13400003 | task service ability error. | 4283| 21900004 | the application task queue is full. | 4284| 21900005 | task mode error. | 4285 4286**Example** 4287 4288 ```ts 4289 import { BusinessError } from '@kit.BasicServicesKit'; 4290 4291 let attachments: Array<request.agent.FormItem> = [{ 4292 name: "createTest", 4293 value: { 4294 filename: "createTest.avi", 4295 mimeType: "application/octet-stream", 4296 path: "./createTest.avi", 4297 } 4298 }]; 4299 let config: request.agent.Config = { 4300 action: request.agent.Action.UPLOAD, 4301 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4302 title: 'createTest', 4303 description: 'Sample code for create task', 4304 mode: request.agent.Mode.BACKGROUND, 4305 overwrite: false, 4306 method: "PUT", 4307 data: attachments, 4308 saveas: "./", 4309 network: request.agent.Network.CELLULAR, 4310 metered: false, 4311 roaming: true, 4312 retry: true, 4313 redirect: true, 4314 index: 0, 4315 begins: 0, 4316 ends: -1, 4317 gauge: false, 4318 precise: false, 4319 token: "it is a secret" 4320 }; 4321 request.agent.create(getContext(), config, async (err: BusinessError, task: request.agent.Task) => { 4322 if (err) { 4323 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4324 return; 4325 } 4326 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4327 await task.start(); 4328 // You need to manually call remove() to end the lifecycle of the task object. 4329 request.agent.remove(task.tid); 4330 }); 4331 ``` 4332 4333> **NOTE** 4334> 4335> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 4336 4337## request.agent.create<sup>10+</sup> 4338 4339create(context: BaseContext, config: Config): Promise<Task> 4340 4341Creates an upload or download task and adds it to the queue. This API uses a promise to return the result. HTTP is supported. 4342 4343 4344**Required permissions**: ohos.permission.INTERNET 4345 4346**Atomic service API**: This API can be used in atomic services since API version 11. 4347 4348**System capability**: SystemCapability.Request.FileTransferAgent 4349 4350**Parameters** 4351 4352| Name| Type| Mandatory| Description| 4353| -------- | -------- | -------- | -------- | 4354| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4355| config | [Config](#config10) | Yes| Task configuration.| 4356 4357**Return value** 4358 4359| Type | Description | 4360| ------------------- | ------------------------- | 4361| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4362 4363**Error codes** 4364 4365For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4366 4367| ID| Error Message| 4368| -------- | -------- | 4369| 201 | permission denied. | 4370| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4371| 13400001 | file operation error. | 4372| 13400003 | task service ability error. | 4373| 21900004 | the application task queue is full. | 4374| 21900005 | task mode error. | 4375 4376**Example** 4377 4378 ```ts 4379 import { BusinessError } from '@kit.BasicServicesKit'; 4380 4381 let attachments: Array<request.agent.FormItem> = [{ 4382 name: "createTest", 4383 value: { 4384 filename: "createTest.avi", 4385 mimeType: "application/octet-stream", 4386 path: "./createTest.avi", 4387 } 4388 }]; 4389 let config: request.agent.Config = { 4390 action: request.agent.Action.UPLOAD, 4391 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4392 title: 'createTest', 4393 description: 'Sample code for create task', 4394 mode: request.agent.Mode.BACKGROUND, 4395 overwrite: false, 4396 method: "PUT", 4397 data: attachments, 4398 saveas: "./", 4399 network: request.agent.Network.CELLULAR, 4400 metered: false, 4401 roaming: true, 4402 retry: true, 4403 redirect: true, 4404 index: 0, 4405 begins: 0, 4406 ends: -1, 4407 gauge: false, 4408 precise: false, 4409 token: "it is a secret" 4410 }; 4411 request.agent.create(getContext(), config).then(async (task: request.agent.Task) => { 4412 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4413 await task.start(); 4414 // You need to manually call remove() to end the lifecycle of the task object. 4415 request.agent.remove(task.tid); 4416 }).catch((err: BusinessError) => { 4417 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4418 }); 4419 ``` 4420 4421> **NOTE** 4422> 4423> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 4424 4425## request.agent.getTask<sup>11+</sup> 4426 4427getTask(context: BaseContext, id: string, token?: string): Promise<Task> 4428 4429Obtains task information based on the task ID. This API uses a promise to return the result. 4430 4431**System capability**: SystemCapability.Request.FileTransferAgent 4432 4433**Parameters** 4434 4435| Name| Type| Mandatory| Description| 4436| -------- | -------- | -------- | -------- | 4437| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4438| id | string | Yes| Task ID.| 4439| token | string | No| Token for task query.| 4440 4441**Return value** 4442 4443| Type | Description | 4444| ------------------- | ------------------------- | 4445| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4446 4447**Error codes** 4448 4449For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4450 4451| ID| Error Message| 4452| -------- | -------- | 4453| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4454| 13400003 | task service ability error. | 4455| 21900006 | task not found. | 4456 4457**Example** 4458 4459 ```ts 4460 import { BusinessError } from '@kit.BasicServicesKit'; 4461 4462 request.agent.getTask(getContext(), "123456").then((task: request.agent.Task) => { 4463 console.info(`Succeeded in querying a task. result: ${task.tid}`); 4464 }).catch((err: BusinessError) => { 4465 console.error(`Failed to query a task, Code: ${err.code}, message: ${err.message}`); 4466 }); 4467 ``` 4468 4469## request.agent.remove<sup>10+</sup> 4470 4471remove(id: string, callback: AsyncCallback<void>): void 4472 4473Removes 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. 4474 4475**Atomic service API**: This API can be used in atomic services since API version 11. 4476 4477**System capability**: SystemCapability.Request.FileTransferAgent 4478 4479**Parameters** 4480 4481| Name| Type| Mandatory| Description| 4482| -------- | -------- | -------- | -------- | 4483| id | string | Yes| Task ID.| 4484| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4485 4486**Error codes** 4487 4488For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4489 4490| ID| Error Message| 4491| -------- | -------- | 4492| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4493| 13400003 | task service ability error. | 4494| 21900006 | task not found. | 4495 4496**Example** 4497 4498 ```ts 4499 import { BusinessError } from '@kit.BasicServicesKit'; 4500 4501 request.agent.remove("123456", (err: BusinessError) => { 4502 if (err) { 4503 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4504 return; 4505 } 4506 console.info(`Succeeded in creating a download task.`); 4507 }); 4508 ``` 4509 4510 4511## request.agent.remove<sup>10+</sup> 4512 4513remove(id: string): Promise<void> 4514 4515Removes 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. 4516 4517**Atomic service API**: This API can be used in atomic services since API version 11. 4518 4519**System capability**: SystemCapability.Request.FileTransferAgent 4520 4521**Parameters** 4522 4523| Name| Type| Mandatory| Description| 4524| -------- | -------- | -------- | -------- | 4525| id | string | Yes| Task ID.| 4526 4527**Return value** 4528 4529| Type | Description | 4530| ------------------- | ------------------------- | 4531| Promise<void> | Promise that returns no value.| 4532 4533**Error codes** 4534 4535For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4536 4537| ID| Error Message| 4538| -------- | -------- | 4539| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4540| 13400003 | task service ability error. | 4541| 21900006 | task not found. | 4542 4543**Example** 4544 4545 ```ts 4546 import { BusinessError } from '@kit.BasicServicesKit'; 4547 4548 request.agent.remove("123456").then(() => { 4549 console.info(`Succeeded in removing a download task. `); 4550 }).catch((err: BusinessError) => { 4551 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4552 }); 4553 ``` 4554 4555 4556## request.agent.show<sup>10+</sup> 4557 4558show(id: string, callback: AsyncCallback<TaskInfo>): void 4559 4560Queries a task details based on the task ID. This API uses an asynchronous callback to return the result. 4561 4562**System capability**: SystemCapability.Request.FileTransferAgent 4563 4564**Parameters** 4565 4566| Name| Type| Mandatory| Description| 4567| -------- | -------- | -------- | -------- | 4568| id | string | Yes| Task ID.| 4569| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | 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.| 4570 4571**Error codes** 4572For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4573 4574| ID| Error Message| 4575| -------- | -------- | 4576| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4577| 13400003 | task service ability error. | 4578| 21900006 | task not found. | 4579 4580**Example** 4581 4582 ```ts 4583 import { BusinessError } from '@kit.BasicServicesKit'; 4584 4585 request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4586 if (err) { 4587 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4588 return; 4589 } 4590 console.info(`Succeeded in showing a upload task.`); 4591 }); 4592 ``` 4593 4594 4595## request.agent.show<sup>10+</sup> 4596 4597show(id: string): Promise<TaskInfo> 4598 4599Queries a task details based on the task ID. This API uses a promise to return the result. 4600 4601**System capability**: SystemCapability.Request.FileTransferAgent 4602 4603**Parameters** 4604 4605| Name| Type| Mandatory| Description| 4606| -------- | -------- | -------- | -------- | 4607| id | string | Yes| Task ID.| 4608 4609**Return value** 4610 4611| Type | Description | 4612| ------------------- | ------------------------- | 4613| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4614 4615**Error codes** 4616For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4617 4618| ID| Error Message| 4619| -------- | -------- | 4620| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4621| 13400003 | task service ability error. | 4622| 21900006 | task not found. | 4623 4624**Example** 4625 4626 ```ts 4627 import { BusinessError } from '@kit.BasicServicesKit'; 4628 4629 request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => { 4630 console.info(`Succeeded in showing a upload task.`); 4631 }).catch((err: BusinessError) => { 4632 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4633 }); 4634 ``` 4635 4636 4637## request.agent.touch<sup>10+</sup> 4638 4639touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void 4640 4641Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result. 4642 4643**System capability**: SystemCapability.Request.FileTransferAgent 4644 4645**Parameters** 4646 4647| Name| Type| Mandatory| Description| 4648| -------- | -------- | -------- | -------- | 4649| id | string | Yes| Task ID.| 4650| token | string | Yes| Token for task query.| 4651| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | 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.| 4652 4653**Error codes** 4654For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4655 4656| ID| Error Message| 4657| -------- | -------- | 4658| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4659| 13400003 | task service ability error. | 4660| 21900006 | task not found. | 4661 4662**Example** 4663 4664 ```ts 4665 import { BusinessError } from '@kit.BasicServicesKit'; 4666 4667 request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4668 if (err) { 4669 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4670 return; 4671 } 4672 console.info(`Succeeded in touching a upload task.`); 4673 }); 4674 ``` 4675 4676 4677## request.agent.touch<sup>10+</sup> 4678 4679touch(id: string, token: string): Promise<TaskInfo> 4680 4681Queries the task details based on the task ID and token. This API uses a promise to return the result. 4682 4683**System capability**: SystemCapability.Request.FileTransferAgent 4684 4685**Parameters** 4686 4687| Name| Type| Mandatory| Description| 4688| -------- | -------- | -------- | -------- | 4689| id | string | Yes| Task ID.| 4690| token | string | Yes| Token for task query.| 4691 4692**Return value** 4693 4694| Type | Description | 4695| ------------------- | ------------------------- | 4696| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4697 4698**Error codes** 4699For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4700 4701| ID| Error Message| 4702| -------- | -------- | 4703| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4704| 13400003 | task service ability error. | 4705| 21900006 | task not found. | 4706 4707**Example** 4708 4709 ```ts 4710 import { BusinessError } from '@kit.BasicServicesKit'; 4711 4712 request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { 4713 console.info(`Succeeded in touching a upload task. `); 4714 }).catch((err: BusinessError) => { 4715 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4716 }); 4717 ``` 4718 4719## request.agent.search<sup>10+</sup> 4720 4721search(callback: AsyncCallback<Array<string>>): void 4722 4723Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4724 4725**System capability**: SystemCapability.Request.FileTransferAgent 4726 4727**Parameters** 4728 4729| Name| Type| Mandatory| Description| 4730| -------- | -------- | -------- | -------- | 4731| 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.| 4732 4733**Error codes** 4734For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4735 4736| ID| Error Message| 4737| -------- | -------- | 4738| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4739| 13400003 | task service ability error. | 4740 4741**Example** 4742 4743 ```ts 4744 import { BusinessError } from '@kit.BasicServicesKit'; 4745 4746 request.agent.search((err: BusinessError, data: Array<string>) => { 4747 if (err) { 4748 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4749 return; 4750 } 4751 console.info(`Succeeded in searching a upload task. `); 4752 }); 4753 ``` 4754 4755## request.agent.search<sup>10+</sup> 4756 4757search(filter: Filter, callback: AsyncCallback<Array<string>>): void 4758 4759Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4760 4761**System capability**: SystemCapability.Request.FileTransferAgent 4762 4763**Parameters** 4764 4765| Name| Type| Mandatory| Description| 4766| -------- | -------- | -------- | -------- | 4767| filter | [Filter](#filter10) | Yes| Filter criteria.| 4768| 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.| 4769 4770**Error codes** 4771For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4772 4773| ID| Error Message| 4774| -------- | -------- | 4775| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4776| 13400003 | task service ability error. | 4777 4778**Example** 4779 4780 ```ts 4781 import { BusinessError } from '@kit.BasicServicesKit'; 4782 4783 let filter: request.agent.Filter = { 4784 action: request.agent.Action.UPLOAD, 4785 mode: request.agent.Mode.BACKGROUND 4786 } 4787 request.agent.search(filter, (err: BusinessError, data: Array<string>) => { 4788 if (err) { 4789 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4790 return; 4791 } 4792 console.info(`Succeeded in searching a upload task. `); 4793 }); 4794 ``` 4795 4796 4797## request.agent.search<sup>10+</sup> 4798 4799search(filter?: Filter): Promise<Array<string>> 4800 4801Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. 4802 4803**System capability**: SystemCapability.Request.FileTransferAgent 4804 4805**Parameters** 4806 4807| Name| Type| Mandatory| Description| 4808| -------- | -------- | -------- | -------- | 4809| filter | [Filter](#filter10) | No| Filter criteria.| 4810 4811**Return value** 4812 4813| Type | Description | 4814| ------------------- | ------------------------- | 4815| Promise<Array<string>> | Promise Promise used to return task ID matches.| 4816 4817**Error codes** 4818For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4819 4820| ID| Error Message| 4821| -------- | -------- | 4822| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4823| 13400003 | task service ability error. | 4824 4825**Example** 4826 4827 ```ts 4828 import { BusinessError } from '@kit.BasicServicesKit'; 4829 4830 let filter: request.agent.Filter = { 4831 action: request.agent.Action.UPLOAD, 4832 mode: request.agent.Mode.BACKGROUND 4833 } 4834 request.agent.search(filter).then((data: Array<string>) => { 4835 console.info(`Succeeded in searching a upload task. `); 4836 }).catch((err: BusinessError) => { 4837 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4838 }); 4839 ``` 4840