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: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol. 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: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol. 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: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol. 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: "image/jpeg" }], // Set type to the MIME type of the HTTP protocol. 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### on('progress') 297 298on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void 299 300Subscribes to upload progress events. This API uses an asynchronous callback to return the result. 301 302> **NOTE** 303> 304> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background. 305 306**System capability**: SystemCapability.MiscServices.Upload 307 308**Parameters** 309 310| Name| Type| Mandatory| Description| 311| -------- | -------- | -------- | -------- | 312| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| 313| callback | function | Yes| Callback used to return the size of the uploaded file and the total size of the file to upload.| 314 315 Parameters of the callback function 316 317| Name| Type| Mandatory| Description| 318| -------- | -------- | -------- | -------- | 319| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| 320| totalSize | number | Yes| Total size of the files to upload, in bytes.| 321 322**Error codes** 323 324For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 325 326| ID| Error Message| 327| -------- | -------- | 328| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 329 330**Example** 331 332<!--code_no_check--> 333 ```ts 334 let upProgressCallback = (uploadedSize: number, totalSize: number) => { 335 console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); 336 }; 337 uploadTask.on('progress', upProgressCallback); 338 ``` 339 340 341### on('headerReceive')<sup>7+</sup> 342 343on(type: 'headerReceive', callback: (header: object) => void): void 344 345Subscribes to HTTP response events for the upload task. This API uses a callback to return the result asynchronously. 346 347**System capability**: SystemCapability.MiscServices.Upload 348 349**Parameters** 350 351| Name| Type| Mandatory| Description| 352| -------- | -------- | -------- | -------- | 353| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response received).| 354| callback | function | Yes| Callback used to return the response content.| 355 356 Parameters of the callback function 357 358| Name| Type| Mandatory| Description| 359| -------- | -------- | -------- | -------- | 360| header | object | Yes| HTTP response.| 361 362**Error codes** 363 364For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 365 366| ID| Error Message| 367| -------- | -------- | 368| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 369 370**Example** 371 372<!--code_no_check--> 373 ```ts 374 let headerCallback = (headers: object) => { 375 console.info("upOnHeader headers:" + JSON.stringify(headers)); 376 }; 377 uploadTask.on('headerReceive', headerCallback); 378 ``` 379 380 381### on('complete' | 'fail')<sup>9+</sup> 382 383 on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; 384 385Subscribes to upload completion or failure events. This API uses an asynchronous callback to return the result. 386 387**System capability**: SystemCapability.MiscServices.Upload 388 389**Parameters** 390 391| Name| Type| Mandatory| Description| 392| -------- | -------- | -------- | -------- | 393| 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.| 394| callback | Callback<Array<[TaskState](#taskstate9)>> | Yes| Callback used to return the result. | 395 396 397**Error codes** 398 399For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 400 401| ID| Error Message| 402| -------- | -------- | 403| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 404 405**Example** 406 407<!--code_no_check--> 408 ```ts 409 let upCompleteCallback = (taskStates: Array<request.TaskState>) => { 410 for (let i = 0; i < taskStates.length; i++) { 411 console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); 412 } 413 }; 414 uploadTask.on('complete', upCompleteCallback); 415 416 let upFailCallback = (taskStates: Array<request.TaskState>) => { 417 for (let i = 0; i < taskStates.length; i++) { 418 console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); 419 } 420 }; 421 uploadTask.on('fail', upFailCallback); 422 ``` 423 424 425### off('progress') 426 427off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void 428 429Unsubscribes from upload progress events. 430 431**System capability**: SystemCapability.MiscServices.Upload 432 433**Parameters** 434 435| Name| Type| Mandatory| Description| 436| -------- | -------- | -------- | -------- | 437| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| 438| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 439 440Parameters of the callback function 441 442| Name| Type| Mandatory| Description| 443| -------- | -------- | -------- | -------- | 444| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| 445| totalSize | number | Yes| Total size of the files to upload, in bytes.| 446 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 the parameters check fails** do not exist. Therefore, this error code 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 the parameters check fails** do not exist. Therefore, this error code 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. From API version 6 to 14, the value contains a maximum of 2048 characters; from API version 15, the value contains a maximum of 8192 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 1105**Error codes** 1106 1107For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1108 1109| ID| Error Message| 1110| -------- | -------- | 1111| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1112 1113**Example** 1114 1115 ```ts 1116import { BusinessError } from '@kit.BasicServicesKit'; 1117 1118try { 1119 // Replace the URL with the HTTP address of the real server. 1120 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1121 let downloadTask: request.DownloadTask = data; 1122 let progressCallback1 = (receivedSize: number, totalSize: number) => { 1123 console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); 1124 }; 1125 let progressCallback2 = (receivedSize: number, totalSize: number) => { 1126 console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); 1127 }; 1128 downloadTask.on('progress', progressCallback1); 1129 downloadTask.on('progress', progressCallback2); 1130 // Unsubscribe from progressCallback1. 1131 downloadTask.off('progress', progressCallback1); 1132 // Unsubscribe from all callbacks of download progress events. 1133 downloadTask.off('progress'); 1134 }).catch((err: BusinessError) => { 1135 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1136 }) 1137} catch (err) { 1138 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1139} 1140 ``` 1141 1142 1143### on('complete'|'pause'|'remove')<sup>7+</sup> 1144 1145on(type: 'complete'|'pause'|'remove', callback:() => void): void 1146 1147Subscribes to download events. This API uses a callback to return the result asynchronously. 1148 1149**System capability**: SystemCapability.MiscServices.Download 1150 1151**Parameters** 1152 1153| Name| Type| Mandatory| Description| 1154| -------- | -------- | -------- | -------- | 1155| 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.| 1156| callback | function | Yes| Callback used to return the result.| 1157 1158**Error codes** 1159 1160For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1161 1162| ID| Error Message| 1163| -------- | -------- | 1164| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1165 1166**Example** 1167 1168 ```ts 1169import { BusinessError } from '@kit.BasicServicesKit'; 1170 1171try { 1172 // Replace the URL with the HTTP address of the real server. 1173 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1174 let downloadTask: request.DownloadTask = data; 1175 let completeCallback = () => { 1176 console.info('Download task completed.'); 1177 }; 1178 downloadTask.on('complete', completeCallback); 1179 1180 let pauseCallback = () => { 1181 console.info('Download task pause.'); 1182 }; 1183 downloadTask.on('pause', pauseCallback); 1184 1185 let removeCallback = () => { 1186 console.info('Download task remove.'); 1187 }; 1188 downloadTask.on('remove', removeCallback); 1189 }).catch((err: BusinessError) => { 1190 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1191 }) 1192} catch (err) { 1193 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1194} 1195 ``` 1196 1197 1198### off('complete'|'pause'|'remove')<sup>7+</sup> 1199 1200off(type: 'complete'|'pause'|'remove', callback?: () => void): void 1201 1202Unsubscribes from download events. 1203 1204**System capability**: SystemCapability.MiscServices.Download 1205 1206**Parameters** 1207 1208| Name| Type| Mandatory| Description| 1209| -------- | -------- | -------- | -------- | 1210| 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.| 1211| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 1212 1213**Error codes** 1214 1215For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1216 1217| ID| Error Message| 1218| -------- | -------- | 1219| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1220 1221**Example** 1222 1223 ```ts 1224import { BusinessError } from '@kit.BasicServicesKit'; 1225 1226try { 1227 // Replace the URL with the HTTP address of the real server. 1228 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1229 let downloadTask: request.DownloadTask = data; 1230 let completeCallback1 = () => { 1231 console.info('Download delete complete notification.'); 1232 }; 1233 let completeCallback2 = () => { 1234 console.info('Download delete complete notification.'); 1235 }; 1236 downloadTask.on('complete', completeCallback1); 1237 downloadTask.on('complete', completeCallback2); 1238 // Unsubscribe from completeCallback1. 1239 downloadTask.off('complete', completeCallback1); 1240 // Unsubscribe from all callbacks of the download completion events. 1241 downloadTask.off('complete'); 1242 1243 let pauseCallback1 = () => { 1244 console.info('Download delete pause notification.'); 1245 }; 1246 let pauseCallback2 = () => { 1247 console.info('Download delete pause notification.'); 1248 }; 1249 downloadTask.on('pause', pauseCallback1); 1250 downloadTask.on('pause', pauseCallback2); 1251 // Unsubscribe from pauseCallback1. 1252 downloadTask.off('pause', pauseCallback1); 1253 // Unsubscribe from all callbacks of the download pause events. 1254 downloadTask.off('pause'); 1255 1256 let removeCallback1 = () => { 1257 console.info('Download delete remove notification.'); 1258 }; 1259 let removeCallback2 = () => { 1260 console.info('Download delete remove notification.'); 1261 }; 1262 downloadTask.on('remove', removeCallback1); 1263 downloadTask.on('remove', removeCallback2); 1264 // Unsubscribe from removeCallback1. 1265 downloadTask.off('remove', removeCallback1); 1266 // Unsubscribe from all callbacks of the download removal events. 1267 downloadTask.off('remove'); 1268 }).catch((err: BusinessError) => { 1269 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1270 }) 1271} catch (err) { 1272 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1273} 1274 1275 ``` 1276 1277 1278### on('fail')<sup>7+</sup> 1279 1280on(type: 'fail', callback: (err: number) => void): void 1281 1282Subscribes to download failure events. This API uses an asynchronous callback to return the result. 1283 1284**System capability**: SystemCapability.MiscServices.Download 1285 1286**Parameters** 1287 1288| Name| Type| Mandatory| Description| 1289| -------- | -------- | -------- | -------- | 1290| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| 1291| callback | function | Yes| Callback for the download task failure event.| 1292 1293 Parameters of the callback function 1294 1295| Name| Type| Mandatory| Description| 1296| -------- | -------- | -------- | -------- | 1297| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#constants).| 1298 1299**Error codes** 1300 1301For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1302 1303| ID| Error Message| 1304| -------- | -------- | 1305| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1306 1307**Example** 1308 1309 ```ts 1310import { BusinessError } from '@kit.BasicServicesKit'; 1311 1312try { 1313 // Replace the URL with the HTTP address of the real server. 1314 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1315 let downloadTask: request.DownloadTask = data; 1316 let failCallback = (err: number) => { 1317 console.error(`Failed to download the task. Code: ${err}`); 1318 }; 1319 downloadTask.on('fail', failCallback); 1320 }).catch((err: BusinessError) => { 1321 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1322 }) 1323} catch (err) { 1324 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1325} 1326 ``` 1327 1328 1329### off('fail')<sup>7+</sup> 1330 1331off(type: 'fail', callback?: (err: number) => void): void 1332 1333Unsubscribes from download failure events. 1334 1335**System capability**: SystemCapability.MiscServices.Download 1336 1337**Parameters** 1338 1339| Name| Type| Mandatory| Description| 1340| -------- | -------- | -------- | -------- | 1341| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| 1342| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 1343 1344**Error codes** 1345 1346For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1347 1348| ID| Error Message| 1349| -------- | -------- | 1350| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1351 1352**Example** 1353 1354 ```ts 1355import { BusinessError } from '@kit.BasicServicesKit'; 1356 1357try { 1358 // Replace the URL with the HTTP address of the real server. 1359 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1360 let downloadTask: request.DownloadTask = data; 1361 let failCallback1 = (err: number) => { 1362 console.error(`Failed to download the task. Code: ${err}`); 1363 }; 1364 let failCallback2 = (err: number) => { 1365 console.error(`Failed to download the task. Code: ${err}`); 1366 }; 1367 downloadTask.on('fail', failCallback1); 1368 downloadTask.on('fail', failCallback2); 1369 // Unsubscribe from failCallback1. 1370 downloadTask.off('fail', failCallback1); 1371 // Unsubscribe from all callbacks of the download failure events. 1372 downloadTask.off('fail'); 1373 }).catch((err: BusinessError) => { 1374 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1375 }) 1376} catch (err) { 1377 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1378} 1379 ``` 1380 1381### delete<sup>9+</sup> 1382 1383delete(): Promise<boolean> 1384 1385Deletes this download task. This API uses a promise to return the result. 1386 1387**Required permissions**: ohos.permission.INTERNET 1388 1389**System capability**: SystemCapability.MiscServices.Download 1390 1391**Return value** 1392 1393| Type| Description| 1394| -------- | -------- | 1395| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1396 1397**Error codes** 1398 1399For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1400 1401| ID| Error Message| 1402| -------- | -------- | 1403| 201 | the permissions check fails | 1404 1405**Example** 1406 1407 ```ts 1408import { BusinessError } from '@kit.BasicServicesKit'; 1409 1410try { 1411 // Replace the URL with the HTTP address of the real server. 1412 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1413 let downloadTask: request.DownloadTask = data; 1414 downloadTask.delete().then((result: boolean) => { 1415 console.info('Succeeded in removing the download task.'); 1416 }).catch((err: BusinessError) => { 1417 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1418 }); 1419 }).catch((err: BusinessError) => { 1420 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1421 }) 1422} catch (err) { 1423 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1424} 1425 ``` 1426 1427> **NOTE** 1428> 1429> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1430 1431 1432### delete<sup>9+</sup> 1433 1434delete(callback: AsyncCallback<boolean>): void 1435 1436Deletes this download task. This API uses an asynchronous callback to return the result. 1437 1438**Required permissions**: ohos.permission.INTERNET 1439 1440**System capability**: SystemCapability.MiscServices.Download 1441 1442**Parameters** 1443 1444| Name| Type| Mandatory| Description| 1445| -------- | -------- | -------- | -------- | 1446| 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.| 1447 1448**Error codes** 1449 1450For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1451 1452| ID| Error Message| 1453| -------- | -------- | 1454| 201 | the permissions check fails | 1455 1456**Example** 1457 1458 ```ts 1459import { BusinessError } from '@kit.BasicServicesKit'; 1460 1461try { 1462 // Replace the URL with the HTTP address of the real server. 1463 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1464 let downloadTask: request.DownloadTask = data; 1465 downloadTask.delete((err: BusinessError, result: boolean) => { 1466 if (err) { 1467 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1468 return; 1469 } 1470 console.info('Succeeded in removing the download task.'); 1471 }); 1472 }).catch((err: BusinessError) => { 1473 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1474 }) 1475} catch (err) { 1476 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1477} 1478 ``` 1479 1480> **NOTE** 1481> 1482> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1483 1484 1485### getTaskInfo<sup>9+</sup> 1486 1487getTaskInfo(): Promise<DownloadInfo> 1488 1489Obtains the information about this download task. This API uses a promise to return the result. 1490 1491**Required permissions**: ohos.permission.INTERNET 1492 1493**System capability**: SystemCapability.MiscServices.Download 1494 1495**Return value** 1496 1497| Type| Description| 1498| -------- | -------- | 1499| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the **DownloadInfo** object.| 1500 1501**Error codes** 1502 1503For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1504 1505| ID| Error Message| 1506| -------- | -------- | 1507| 201 | the permissions check fails | 1508 1509**Example** 1510 1511 ```ts 1512import { BusinessError } from '@kit.BasicServicesKit'; 1513 1514try { 1515 // Replace the URL with the HTTP address of the real server. 1516 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1517 let downloadTask: request.DownloadTask = data; 1518 downloadTask.getTaskInfo().then((downloadInfo: request.DownloadInfo) => { 1519 console.info('Succeeded in querying the download task') 1520 }).catch((err: BusinessError) => { 1521 console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) 1522 }); 1523 }).catch((err: BusinessError) => { 1524 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1525 }) 1526} catch (err) { 1527 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1528} 1529 ``` 1530 1531> **NOTE** 1532> 1533> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1534 1535 1536### getTaskInfo<sup>9+</sup> 1537 1538getTaskInfo(callback: AsyncCallback<DownloadInfo>): void 1539 1540Obtains this download task. This API uses an asynchronous callback to return the result. 1541 1542**Required permissions**: ohos.permission.INTERNET 1543 1544**System capability**: SystemCapability.MiscServices.Download 1545 1546**Parameters** 1547 1548| Name| Type| Mandatory| Description| 1549| -------- | -------- | -------- | -------- | 1550| 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.| 1551 1552**Error codes** 1553 1554For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1555 1556| ID| Error Message| 1557| -------- | -------- | 1558| 201 | the permissions check fails | 1559 1560**Example** 1561 1562 ```ts 1563import { BusinessError } from '@kit.BasicServicesKit'; 1564 1565try { 1566 // Replace the URL with the HTTP address of the real server. 1567 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1568 let downloadTask: request.DownloadTask = data; 1569 downloadTask.getTaskInfo((err: BusinessError, downloadInfo: request.DownloadInfo) => { 1570 if (err) { 1571 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 1572 } else { 1573 console.info('Succeeded in querying the download mimeType'); 1574 } 1575 }); 1576 }).catch((err: BusinessError) => { 1577 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1578 }) 1579} catch (err) { 1580 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1581} 1582 ``` 1583 1584> **NOTE** 1585> 1586> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1587 1588 1589### getTaskMimeType<sup>9+</sup> 1590 1591getTaskMimeType(): Promise<string> 1592 1593Obtains **MimeType** (that is, media type of resources) of a download task. This API uses a promise to return the result. 1594 1595**Required permissions**: ohos.permission.INTERNET 1596 1597**System capability**: SystemCapability.MiscServices.Download 1598 1599**Return value** 1600 1601| Type| Description| 1602| -------- | -------- | 1603| Promise<string> | Promise used to return the **MimeType** object.| 1604 1605**Error codes** 1606 1607For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1608 1609| ID| Error Message| 1610| -------- | -------- | 1611| 201 | the permissions check fails | 1612 1613**Example** 1614 1615 ```ts 1616import { BusinessError } from '@kit.BasicServicesKit'; 1617 1618try { 1619 // Replace the URL with the HTTP address of the real server. 1620 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1621 let downloadTask: request.DownloadTask = data; 1622 downloadTask.getTaskMimeType().then((data: string) => { 1623 console.info('Succeeded in querying the download MimeType'); 1624 }).catch((err: BusinessError) => { 1625 console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) 1626 }); 1627 }).catch((err: BusinessError) => { 1628 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1629 }) 1630} catch (err) { 1631 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1632} 1633 ``` 1634 1635> **NOTE** 1636> 1637> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1638 1639 1640### getTaskMimeType<sup>9+</sup> 1641 1642getTaskMimeType(callback: AsyncCallback<string>): void; 1643 1644Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. 1645 1646**Required permissions**: ohos.permission.INTERNET 1647 1648**System capability**: SystemCapability.MiscServices.Download 1649 1650**Parameters** 1651 1652| Name| Type| Mandatory| Description| 1653| -------- | -------- | -------- | -------- | 1654| 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.| 1655 1656**Error codes** 1657 1658For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1659 1660| ID| Error Message| 1661| -------- | -------- | 1662| 201 | the permissions check fails | 1663 1664**Example** 1665 1666 ```ts 1667import { BusinessError } from '@kit.BasicServicesKit'; 1668 1669try { 1670 // Replace the URL with the HTTP address of the real server. 1671 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1672 let downloadTask: request.DownloadTask = data; 1673 downloadTask.getTaskMimeType((err: BusinessError, data: string) => { 1674 if (err) { 1675 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 1676 } else { 1677 console.info('Succeeded in querying the download mimeType'); 1678 } 1679 }); 1680 }).catch((err: BusinessError) => { 1681 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1682 }) 1683} catch (err) { 1684 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1685} 1686 ``` 1687 1688> **NOTE** 1689> 1690> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1691 1692 1693### suspend<sup>9+</sup> 1694 1695suspend(): Promise<boolean> 1696 1697Suspends this download task. This API uses a promise to return the result. 1698 1699**Required permissions**: ohos.permission.INTERNET 1700 1701**System capability**: SystemCapability.MiscServices.Download 1702 1703**Return value** 1704 1705| Type| Description| 1706| -------- | -------- | 1707| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1708 1709**Error codes** 1710 1711For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1712 1713| ID| Error Message| 1714| -------- | -------- | 1715| 201 | the permissions check fails | 1716 1717**Example** 1718 1719 ```ts 1720import { BusinessError } from '@kit.BasicServicesKit'; 1721 1722try { 1723 // Replace the URL with the HTTP address of the real server. 1724 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1725 let downloadTask: request.DownloadTask = data; 1726 downloadTask.suspend().then((result: boolean) => { 1727 console.info('Succeeded in pausing the download task.'); 1728 }).catch((err: BusinessError) => { 1729 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 1730 }); 1731 }).catch((err: BusinessError) => { 1732 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1733 }) 1734} catch (err) { 1735 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1736} 1737 ``` 1738 1739> **NOTE** 1740> 1741> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1742 1743 1744### suspend<sup>9+</sup> 1745 1746suspend(callback: AsyncCallback<boolean>): void 1747 1748Suspends this download task. This API uses an asynchronous callback to return the result. 1749 1750**Required permissions**: ohos.permission.INTERNET 1751 1752**System capability**: SystemCapability.MiscServices.Download 1753 1754**Parameters** 1755 1756| Name| Type| Mandatory| Description| 1757| -------- | -------- | -------- | -------- | 1758| 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.| 1759 1760**Error codes** 1761 1762For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1763 1764| ID| Error Message| 1765| -------- | -------- | 1766| 201 | the permissions check fails | 1767 1768**Example** 1769 1770 ```ts 1771import { BusinessError } from '@kit.BasicServicesKit'; 1772 1773try { 1774 // Replace the URL with the HTTP address of the real server. 1775 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1776 let downloadTask: request.DownloadTask = data; 1777 downloadTask.suspend((err: BusinessError, result: boolean) => { 1778 if (err) { 1779 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 1780 return; 1781 } 1782 console.info('Succeeded in pausing the download task.'); 1783 }); 1784 }).catch((err: BusinessError) => { 1785 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1786 }) 1787} catch (err) { 1788 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1789} 1790 ``` 1791 1792> **NOTE** 1793> 1794> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1795 1796 1797### restore<sup>9+</sup> 1798 1799restore(): Promise<boolean> 1800 1801Restores this download task. This API uses a promise to return the result. 1802 1803**Required permissions**: ohos.permission.INTERNET 1804 1805**System capability**: SystemCapability.MiscServices.Download 1806 1807**Return value** 1808 1809| Type| Description| 1810| -------- | -------- | 1811| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1812 1813**Error codes** 1814 1815For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1816 1817| ID| Error Message| 1818| -------- | -------- | 1819| 201 | the permissions check fails | 1820 1821**Example** 1822 1823 ```ts 1824import { BusinessError } from '@kit.BasicServicesKit'; 1825 1826try { 1827 // Replace the URL with the HTTP address of the real server. 1828 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1829 let downloadTask: request.DownloadTask = data; 1830 downloadTask.restore().then((result: boolean) => { 1831 console.info('Succeeded in resuming the download task.') 1832 }).catch((err: BusinessError) => { 1833 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 1834 }); 1835 }).catch((err: BusinessError) => { 1836 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1837 }) 1838} catch (err) { 1839 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1840} 1841 ``` 1842 1843> **NOTE** 1844> 1845> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1846 1847 1848### restore<sup>9+</sup> 1849 1850restore(callback: AsyncCallback<boolean>): void 1851 1852Restores this download task. This API uses an asynchronous callback to return the result. 1853 1854**Required permissions**: ohos.permission.INTERNET 1855 1856**System capability**: SystemCapability.MiscServices.Download 1857 1858**Parameters** 1859 1860| Name| Type| Mandatory| Description| 1861| -------- | -------- | -------- | -------- | 1862| 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.| 1863 1864**Error codes** 1865 1866For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1867 1868| ID| Error Message| 1869| -------- | -------- | 1870| 201 | the permissions check fails | 1871 1872**Example** 1873 1874 ```ts 1875import { BusinessError } from '@kit.BasicServicesKit'; 1876 1877try { 1878 // Replace the URL with the HTTP address of the real server. 1879 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1880 let downloadTask: request.DownloadTask = data; 1881 downloadTask.restore((err: BusinessError, result: boolean) => { 1882 if (err) { 1883 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 1884 return; 1885 } 1886 console.info('Succeeded in resuming the download task.'); 1887 }); 1888 }).catch((err: BusinessError) => { 1889 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1890 }) 1891} catch (err) { 1892 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1893} 1894 ``` 1895 1896> **NOTE** 1897> 1898> The scenarios for triggering error code **401 the parameters check fails** do not exist. Therefore, this error code is removed from API version 12. 1899 1900 1901### remove<sup>(deprecated)</sup> 1902 1903remove(): Promise<boolean> 1904 1905Removes this download task. This API uses a promise to return the result. 1906 1907> **NOTE** 1908> 1909> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-2) instead. 1910 1911**Required permissions**: ohos.permission.INTERNET 1912 1913**System capability**: SystemCapability.MiscServices.Download 1914 1915**Return value** 1916 1917| Type| Description| 1918| -------- | -------- | 1919| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 1920 1921**Error codes** 1922 1923For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1924 1925| ID| Error Message| 1926| -------- | -------- | 1927| 201 | the permissions check fails | 1928 1929**Example** 1930 1931 ```js 1932 downloadTask.remove().then((result) => { 1933 console.info('Succeeded in removing the download task.'); 1934 }).catch ((err) => { 1935 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1936 }); 1937 ``` 1938 1939 1940### remove<sup>(deprecated)</sup> 1941 1942remove(callback: AsyncCallback<boolean>): void 1943 1944Removes this download task. This API uses an asynchronous callback to return the result. 1945 1946> **NOTE** 1947> 1948> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-3) instead. 1949 1950**Required permissions**: ohos.permission.INTERNET 1951 1952**System capability**: SystemCapability.MiscServices.Download 1953 1954**Parameters** 1955 1956| Name| Type| Mandatory| Description| 1957| -------- | -------- | -------- | -------- | 1958| 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.| 1959 1960**Error codes** 1961 1962For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1963 1964| ID| Error Message| 1965| -------- | -------- | 1966| 201 | the permissions check fails | 1967 1968**Example** 1969 1970 ```js 1971 downloadTask.remove((err, result)=>{ 1972 if(err) { 1973 console.error(`Failed to remove the download task. Code: ${err.code}, message: ${err.message}`); 1974 return; 1975 } 1976 console.info('Succeeded in removing the download task.'); 1977 }); 1978 ``` 1979 1980 1981### query<sup>(deprecated)</sup> 1982 1983query(): Promise<DownloadInfo> 1984 1985Queries this download task. This API uses a promise to return the result. 1986 1987> **NOTE** 1988> 1989> 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. 1990 1991**Required permissions**: ohos.permission.INTERNET 1992 1993**System capability**: SystemCapability.MiscServices.Download 1994 1995**Return value** 1996 1997| Type| Description| 1998| -------- | -------- | 1999| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the **DownloadInfo** object.| 2000 2001**Error codes** 2002 2003For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2004 2005| ID| Error Message| 2006| -------- | -------- | 2007| 201 | the permissions check fails | 2008 2009**Example** 2010 2011 ```js 2012 downloadTask.query().then((downloadInfo) => { 2013 console.info('Succeeded in querying the download task.') 2014 }) .catch((err) => { 2015 console.error(`Failed to query the download task. Code: ${err.code}, message: ${err.message}`) 2016 }); 2017 ``` 2018 2019 2020### query<sup>(deprecated)</sup> 2021 2022query(callback: AsyncCallback<DownloadInfo>): void 2023 2024Queries this download task. This API uses an asynchronous callback to return the result. 2025 2026> **NOTE** 2027> 2028> 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. 2029 2030**Required permissions**: ohos.permission.INTERNET 2031 2032**System capability**: SystemCapability.MiscServices.Download 2033 2034**Parameters** 2035 2036| Name| Type| Mandatory| Description| 2037| -------- | -------- | -------- | -------- | 2038| 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.| 2039 2040**Error codes** 2041 2042For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2043 2044| ID| Error Message| 2045| -------- | -------- | 2046| 201 | the permissions check fails | 2047 2048**Example** 2049 2050 ```js 2051 downloadTask.query((err, downloadInfo)=>{ 2052 if(err) { 2053 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 2054 } else { 2055 console.info('Succeeded in querying the download task.'); 2056 } 2057 }); 2058 ``` 2059 2060 2061### queryMimeType<sup>(deprecated)</sup> 2062 2063queryMimeType(): Promise<string> 2064 2065Queries the **MimeType** of this download task. This API uses a promise to return the result. 2066 2067> **NOTE** 2068> 2069> 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. 2070 2071**Required permissions**: ohos.permission.INTERNET 2072 2073**System capability**: SystemCapability.MiscServices.Download 2074 2075**Return value** 2076 2077| Type| Description| 2078| -------- | -------- | 2079| Promise<string> | Promise used to return the **MimeType** object.| 2080 2081**Error codes** 2082 2083For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2084 2085| ID| Error Message| 2086| -------- | -------- | 2087| 201 | the permissions check fails | 2088 2089**Example** 2090 2091 ```js 2092 downloadTask.queryMimeType().then((data) => { 2093 console.info('Succeeded in querying the download MimeType.'); 2094 }).catch((err) => { 2095 console.error(`Failed to query the download MimeType. Code: ${err.code}, message: ${err.message}`) 2096 }); 2097 ``` 2098 2099 2100### queryMimeType<sup>(deprecated)</sup> 2101 2102queryMimeType(callback: AsyncCallback<string>): void; 2103 2104Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. 2105 2106> **NOTE** 2107> 2108> 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. 2109 2110**Required permissions**: ohos.permission.INTERNET 2111 2112**System capability**: SystemCapability.MiscServices.Download 2113 2114**Parameters** 2115 2116| Name| Type| Mandatory| Description| 2117| -------- | -------- | -------- | -------- | 2118| 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.| 2119 2120**Error codes** 2121 2122For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2123 2124| ID| Error Message| 2125| -------- | -------- | 2126| 201 | the permissions check fails | 2127 2128**Example** 2129 2130 ```js 2131 downloadTask.queryMimeType((err, data)=>{ 2132 if(err) { 2133 console.error(`Failed to query the download mimeType. Code: ${err.code}, message: ${err.message}`); 2134 } else { 2135 console.info('Succeeded in querying the download mimeType.'); 2136 } 2137 }); 2138 ``` 2139 2140 2141### pause<sup>(deprecated)</sup> 2142 2143pause(): Promise<void> 2144 2145Pauses this download task. This API uses a promise to return the result. 2146 2147> **NOTE** 2148> 2149> 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. 2150 2151**Required permissions**: ohos.permission.INTERNET 2152 2153**System capability**: SystemCapability.MiscServices.Download 2154 2155**Return value** 2156 2157| Type| Description| 2158| -------- | -------- | 2159| Promise<void> | Promise that returns no value.| 2160 2161**Error codes** 2162 2163For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2164 2165| ID| Error Message| 2166| -------- | -------- | 2167| 201 | the permissions check fails | 2168 2169**Example** 2170 2171 ```js 2172 downloadTask.pause().then((result) => { 2173 console.info('Succeeded in pausing the download task.'); 2174 }).catch((err) => { 2175 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 2176 }); 2177 ``` 2178 2179 2180### pause<sup>(deprecated)</sup> 2181 2182pause(callback: AsyncCallback<void>): void 2183 2184> **NOTE** 2185> 2186> 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. 2187 2188Pauses this download task. This API uses an asynchronous callback to return the result. 2189 2190**Required permissions**: ohos.permission.INTERNET 2191 2192**System capability**: SystemCapability.MiscServices.Download 2193 2194**Parameters** 2195 2196| Name| Type| Mandatory| Description| 2197| -------- | -------- | -------- | -------- | 2198| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 2199 2200**Error codes** 2201 2202For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2203 2204| ID| Error Message| 2205| -------- | -------- | 2206| 201 | the permissions check fails | 2207 2208**Example** 2209 2210 ```js 2211 downloadTask.pause((err, result)=>{ 2212 if(err) { 2213 console.error(`Failed to pause the download task. Code: ${err.code}, message: ${err.message}`); 2214 return; 2215 } 2216 console.info('Succeeded in pausing the download task.'); 2217 }); 2218 ``` 2219 2220 2221### resume<sup>(deprecated)</sup> 2222 2223resume(): Promise<void> 2224 2225Resumes this download task. This API uses a promise to return the result. 2226 2227> **NOTE** 2228> 2229> 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. 2230 2231**Required permissions**: ohos.permission.INTERNET 2232 2233**System capability**: SystemCapability.MiscServices.Download 2234 2235**Return value** 2236 2237| Type| Description| 2238| -------- | -------- | 2239| Promise<void> | Promise that returns no value.| 2240 2241**Error codes** 2242 2243For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2244 2245| ID| Error Message| 2246| -------- | -------- | 2247| 201 | the permissions check fails | 2248 2249**Example** 2250 2251 ```js 2252 downloadTask.resume().then((result) => { 2253 console.info('Succeeded in resuming the download task.') 2254 }).catch((err) => { 2255 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 2256 }); 2257 ``` 2258 2259 2260### resume<sup>(deprecated)</sup> 2261 2262resume(callback: AsyncCallback<void>): void 2263 2264> **NOTE** 2265> 2266> 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. 2267 2268Resumes this download task. This API uses an asynchronous callback to return the result. 2269 2270**Required permissions**: ohos.permission.INTERNET 2271 2272**System capability**: SystemCapability.MiscServices.Download 2273 2274**Parameters** 2275 2276| Name| Type| Mandatory| Description| 2277| -------- | -------- | -------- | -------- | 2278| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 2279 2280**Error codes** 2281 2282For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2283 2284| ID| Error Message| 2285| -------- | -------- | 2286| 201 | the permissions check fails | 2287 2288**Example** 2289 2290 ```js 2291 downloadTask.resume((err, result)=>{ 2292 if (err) { 2293 console.error(`Failed to resume the download task. Code: ${err.code}, message: ${err.message}`); 2294 return; 2295 } 2296 console.info('Succeeded in resuming the download task.'); 2297 }); 2298 ``` 2299 2300 2301## DownloadConfig 2302Defines the download task configuration. 2303 2304**System capability**: SystemCapability.MiscServices.Download 2305 2306| Name| Type| Mandatory| Description| 2307| -------- | -------- | -------- | -------- | 2308| url | string | Yes| Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; from API version 15, the value contains a maximum of 8192 characters.| 2309| header | Object | No| HTTPS flag header to be included in the download request.| 2310| 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| 2311| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.<br>- **true**: allowed<br>- **false**: not allowed| 2312| description | string | No| Description of the download session.| 2313| 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.| 2314| 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| 2315| title | string | No| Download task name.| 2316| 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.| 2317 2318 2319## DownloadInfo<sup>7+</sup> 2320Defines the download task information, which is the callback parameter of the [getTaskInfo<sup>9+</sup>](#gettaskinfo9) API. 2321 2322**System capability**: SystemCapability.MiscServices.Download 2323 2324| Name| Type|Mandatory| Description| 2325| -------- | -------- | -------- | -------- | 2326| downloadId | number |Yes| ID of the download task.| 2327| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#constants).| 2328| fileName | string |Yes| Name of the downloaded file.| 2329| filePath | string |Yes| URI of the saved file.| 2330| pausedReason | number |Yes| Cause of download pause. The value can be any constant in [Causes of Download Pause](#constants).| 2331| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#constants).| 2332| targetURI | string |Yes| URI of the downloaded file.| 2333| downloadTitle | string |Yes| Name of the download task.| 2334| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| 2335| description | string |Yes| Description of the download task.| 2336| downloadedBytes | number |Yes| Real-time download size, in bytes.| 2337 2338## Action<sup>10+</sup> 2339 2340Defines action options. 2341 2342**Atomic service API**: This API can be used in atomic services since API version 11. 2343 2344**System capability**: SystemCapability.Request.FileTransferAgent 2345 2346| Name| Value|Description| 2347| -------- | -------- |-------- | 2348| DOWNLOAD | 0 |Download.| 2349| UPLOAD | 1 |Upload.| 2350 2351 2352## Mode<sup>10+</sup> 2353Defines mode options.<br> 2354After an application is switched to the background for a period of time, background tasks are not affected but foreground tasks will fail or pause. 2355 2356**Atomic service API**: This API can be used in atomic services since API version 11. 2357 2358**System capability**: SystemCapability.Request.FileTransferAgent 2359 2360| Name| Value|Description| 2361| -------- | -------- |-------- | 2362| BACKGROUND | 0 |Background task.| 2363| FOREGROUND | 1 |Foreground task.| 2364 2365## Network<sup>10+</sup> 2366 2367Defines network options.<br> 2368If 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. 2369 2370**Atomic service API**: This API can be used in atomic services since API version 11. 2371 2372**System capability**: SystemCapability.Request.FileTransferAgent 2373 2374| Name| Value|Description| 2375| -------- | -------- |-------- | 2376| ANY | 0 |Network of any type.| 2377| WIFI | 1 |Wi-Fi network.| 2378| CELLULAR | 2 |Cellular data network.| 2379 2380## BroadcastEvent<sup>11+</sup> 2381 2382Defines a custom system event. You can use a common event API to obtain the event. 2383The 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. 2384 2385Use 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. 2386 2387<!--Del--> 2388For 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--> 2389 2390**System capability**: SystemCapability.Request.FileTransferAgent 2391 2392| Name| Value| Description | 2393| -------- | ------- |-----------| 2394| COMPLETE | 'ohos.request.event.COMPLETE' | Task completion event.| 2395 2396## FileSpec<sup>10+</sup> 2397Provides the file information of a table item. 2398 2399**Atomic service API**: This API can be used in atomic services since API version 11. 2400 2401**System capability**: SystemCapability.Request.FileTransferAgent 2402 2403| Name| Type| Mandatory| Description| 2404| -------- | -------- | -------- | -------- | 2405| 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.| 2406| mimeType | string | No| MIME type of the file, which is obtained from the file name.| 2407| filename | string | No| File name. The default value is obtained from the file path.| 2408| extras | object | No| Additional information. This parameter is not included in HTTP requests.| 2409 2410 2411## FormItem<sup>10+</sup> 2412Describes the form item of a task. 2413 2414**Atomic service API**: This API can be used in atomic services since API version 11. 2415 2416**System capability**: SystemCapability.Request.FileTransferAgent 2417 2418| Name| Type| Mandatory| Description| 2419| -------- | -------- | -------- | -------- | 2420| name | string | Yes| Form parameter name.| 2421| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes| Form parameter value.| 2422 2423 2424## Config<sup>10+</sup> 2425Provides the configuration information of an upload or download task. 2426 2427**System capability**: SystemCapability.Request.FileTransferAgent 2428 2429| Name| Type| Mandatory| Description| 2430| -------- | -------- | -------- | -------- | 2431| 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.| 2432| url | string | Yes| Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; from API version 15, the value contains a maximum of 8192 characters.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2433| 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.| 2434| 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.| 2435| 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.| 2436| 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.| 2437| 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.| 2438| 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.| 2439| 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)>. Since API version 15, a maximum of 100 files can be uploaded in a single task. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2440| 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.| 2441| 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.| 2442| 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.| 2443| 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.| 2444| 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.| 2445| 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.| 2446| 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.| 2447| 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.| 2448| 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.| 2449| 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.| 2450| 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.| 2451| 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.| 2452| 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.| 2453| 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**| 2454| 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.| 2455| multipart<sup>15+</sup> | boolean | No| Whether to upload files in multipart/form-data format using a single request. A single request is used for each file if the value is **false** and for multiple files if the value is **true**. The default value is **false**.| 2456 2457## State<sup>10+</sup> 2458 2459Defines the current task status. 2460 2461**Atomic service API**: This API can be used in atomic services since API version 11. 2462 2463**System capability**: SystemCapability.Request.FileTransferAgent 2464 2465| Name| Value|Description| 2466| -------- | -------- |-------- | 2467| INITIALIZED | 0x00 |The task is initialized based on the configuration specified in [Config](#config10).| 2468| WAITING | 0x10 |The task lacks resources for running or the resources for retries do not match the network status.| 2469| RUNNING | 0x20 |The task is being executed.| 2470| RETRYING | 0x21 |The task has failed at least once and is being executed again.| 2471| PAUSED | 0x30 |The task is suspended and will be resumed later.| 2472| STOPPED | 0x31 |The task is stopped.| 2473| COMPLETED | 0x40 |The task is complete.| 2474| FAILED | 0x41 |The task fails.| 2475| REMOVED | 0x50 |The task is removed.| 2476 2477 2478## Progress<sup>10+</sup> 2479Describes the data structure of the task progress. 2480 2481**Atomic service API**: This API can be used in atomic services since API version 11. 2482 2483**System capability**: SystemCapability.Request.FileTransferAgent 2484 2485| Name| Type| Mandatory| Description | 2486| -------- | -------- | -------- |---------------------------------------------------------------------| 2487| state | [State](#state10) | Yes| Current task status. | 2488| index | number | Yes| Index of the file that is being processed in the task. | 2489| processed | number | Yes| Size of processed data in the current file in the task, in bytes. | 2490| 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**.| 2491| extras | object | No| Extra information of the task, for example, the header and body of the response from the server. | 2492 2493 2494## Faults<sup>10+</sup> 2495 2496Defines the cause of a task failure. 2497 2498**Atomic service API**: This API can be used in atomic services since API version 11. 2499 2500**System capability**: SystemCapability.Request.FileTransferAgent 2501 2502| Name| Value| Description | 2503| -------- | -------- |--------------------------------------------------------------------------------| 2504| OTHERS | 0xFF | Other fault. | 2505| DISCONNECTED | 0x00 | Network disconnection. | 2506| TIMEOUT | 0x10 | Timeout. | 2507| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | 2508| 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. | 2509| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | 2510| DNS<sup>12+</sup> | 0x50 | DNS resolution error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2511| TCP<sup>12+</sup> | 0x60 | TCP connection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2512| 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.| 2513| REDIRECT<sup>12+</sup> | 0x80 | Redirection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2514 2515> **NOTE** 2516> 2517> 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. 2518 2519## Filter<sup>10+</sup> 2520Defines the filter criteria. 2521 2522**System capability**: SystemCapability.Request.FileTransferAgent 2523 2524| Name| Type| Mandatory| Description| 2525| -------- | -------- | -------- | -------- | 2526| before | number | No| Unix timestamp of the end time, in milliseconds. The default value is the invoking time.| 2527| after | number | No| Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours.| 2528| state | [State](#state10) | No| Task state.| 2529| action | [Action](#action10) | No| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2530| mode | [Mode](#mode10) | No| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.<br>- No value: All tasks are queried.| 2531 2532## TaskInfo<sup>10+</sup> 2533Defines the data structure of the task information for query. The fields available vary depending on the query type. 2534 2535**System capability**: SystemCapability.Request.FileTransferAgent 2536 2537| Name| Type| Mandatory| Description| 2538| -------- | -------- | -------- | -------- | 2539| saveas | string | No| Path for storing downloaded files.| 2540| 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).| 2541| 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).| 2542| tid | string | Yes| Task ID.| 2543| title | string | Yes| Task title.| 2544| description | string | Yes| Task description.| 2545| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2546| mode | [Mode](#mode10) | Yes| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.| 2547| 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.| 2548| mimeType | string | Yes| MIME type in the task configuration.| 2549| progress | [Progress](#progress10) | Yes| Task progress.| 2550| gauge | boolean | Yes| Whether to send progress notifications. This parameter applies only to background tasks.| 2551| 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: 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).| 2552| mtime | number | Yes| Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device.| 2553| retry | boolean | Yes| Whether automatic retry is enabled for the task. This parameter applies only to background tasks.| 2554| tries | number | Yes| Number of retries of the task.| 2555| faults | [Faults](#faults10) | Yes| Failure cause of the task.| 2556| reason | string | Yes| Reason why the task is waiting, failed, stopped, or paused.| 2557| extras | object | No| Extra information of the task.| 2558| notification<sup>15+</sup> | [Notification](#notification15) | No| Custom settings for the notification bar.| 2559 2560## HttpResponse<sup>12+</sup> 2561Describes the data structure of the task response header. 2562 2563**Atomic service API**: This API can be used in atomic services since API version 12. 2564 2565**System capability**: SystemCapability.Request.FileTransferAgent 2566 2567| Name| Type| Mandatory| Description| 2568| -------- | -------- | -------- | -------- | 2569| version | string | Yes| HTTP version.| 2570| statusCode | number | Yes| HTTP response status code.| 2571| reason | string | Yes| HTTP response cause.| 2572| headers | Map<string, Array<string>> | Yes| HTTP response header.| 2573 2574## Notification<sup>15+</sup> 2575 2576Describes the custom information of the notification bar. 2577 2578**System capability**: SystemCapability.Request.FileTransferAgent 2579 2580| Name | Type | Mandatory| Description | 2581|---------|--------|----|-----------------------------------------| 2582| title | string | No | Custom title, with a maximum of 1024 bytes. The default title is used if the value is not set.| 2583| text | string | No | Custom text, with a maximum of 3072 bytes. The default title is used if the value is not set. | 2584 2585## GroupConfig<sup>15+</sup> 2586 2587Describes group configuration options for download tasks. 2588 2589**System capability**: SystemCapability.Request.FileTransferAgent 2590 2591| Name | Type | Mandatory| Description | 2592|--------------|-----------------------------------------------|----|--------------------------------------------------------------| 2593| gauge | boolean | No | Progress notification policy of a background task. Set value to **true**, the progress, success, and failure notifications are displayed; set value to **false**, only the success and failure notifications are displayed. The default value is **false**.| 2594| notification | [Notification](#notification15) | No | Custom settings for the notification bar. | 2595 2596## Task<sup>10+</sup> 2597Implements 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). 2598 2599### Attributes 2600Task attributes include the task ID and task configuration. 2601 2602**Atomic service API**: This API can be used in atomic services since API version 11. 2603 2604**System capability**: SystemCapability.Request.FileTransferAgent 2605 2606| Name| Type| Mandatory| Description| 2607| -------- | -------- | -------- | -------- | 2608| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.| 2609| config | [Config](#config10) | Yes| Task configuration.| 2610 2611> **NOTE** 2612> 2613> The **Task** object and its mounting callback function are released and automatically reclaimed by the system after the **remove** method is called. 2614 2615### on('progress')<sup>10+</sup> 2616 2617on(event: 'progress', callback: (progress: [Progress](#progress10)) => void): void 2618 2619Subscribes to task progress changes. This API uses an asynchronous callback to return the result. 2620 2621**Atomic service API**: This API can be used in atomic services since API version 11. 2622 2623**System capability**: SystemCapability.Request.FileTransferAgent 2624 2625**Parameters** 2626 2627| Name| Type| Mandatory| Description| 2628| -------- | -------- | -------- | -------- | 2629| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 2630| callback | function | Yes| Callback used to return the data structure of the task progress.| 2631 2632**Error codes** 2633 2634For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2635 2636| ID| Error Message| 2637| -------- | -------- | 2638| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2639 2640**Example** 2641 2642 ```ts 2643 import { BusinessError } from '@kit.BasicServicesKit'; 2644 2645 let attachments: Array<request.agent.FormItem> = [{ 2646 name: "taskOnTest", 2647 value: { 2648 filename: "taskOnTest.avi", 2649 mimeType: "application/octet-stream", 2650 path: "./taskOnTest.avi", 2651 } 2652 }]; 2653 let config: request.agent.Config = { 2654 action: request.agent.Action.UPLOAD, 2655 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2656 title: 'taskOnTest', 2657 description: 'Sample code for event listening', 2658 mode: request.agent.Mode.FOREGROUND, 2659 overwrite: false, 2660 method: "PUT", 2661 data: attachments, 2662 saveas: "./", 2663 network: request.agent.Network.CELLULAR, 2664 metered: false, 2665 roaming: true, 2666 retry: true, 2667 redirect: true, 2668 index: 0, 2669 begins: 0, 2670 ends: -1, 2671 gauge: false, 2672 precise: false, 2673 token: "it is a secret" 2674 }; 2675 let createOnCallback = (progress: request.agent.Progress) => { 2676 console.info('upload task progress.'); 2677 }; 2678 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2679 task.on('progress', createOnCallback); 2680 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2681 task.start(); 2682 }).catch((err: BusinessError) => { 2683 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2684 }); 2685 ``` 2686 2687> **NOTE** 2688> 2689> 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). 2690 2691### on('completed')<sup>10+</sup> 2692 2693on(event: 'completed', callback: (progress: [Progress](#progress10)) => void): void 2694 2695Subscribes to task completion events. This API uses an asynchronous callback to return the result. 2696 2697**Atomic service API**: This API can be used in atomic services since API version 11. 2698 2699**System capability**: SystemCapability.Request.FileTransferAgent 2700 2701**Parameters** 2702 2703| Name| Type| Mandatory| Description| 2704| -------- | -------- | -------- | -------- | 2705| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 2706| callback | function | Yes| Callback used to return the data structure of the task progress.| 2707 2708**Error codes** 2709 2710For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2711 2712| ID| Error Message| 2713| -------- | -------- | 2714| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2715 2716**Example** 2717 2718 ```ts 2719 import { BusinessError } from '@kit.BasicServicesKit'; 2720 2721 let attachments: Array<request.agent.FormItem> = [{ 2722 name: "taskOnTest", 2723 value: { 2724 filename: "taskOnTest.avi", 2725 mimeType: "application/octet-stream", 2726 path: "./taskOnTest.avi", 2727 } 2728 }]; 2729 let config: request.agent.Config = { 2730 action: request.agent.Action.UPLOAD, 2731 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2732 title: 'taskOnTest', 2733 description: 'Sample code for event listening', 2734 mode: request.agent.Mode.FOREGROUND, 2735 overwrite: false, 2736 method: "PUT", 2737 data: attachments, 2738 saveas: "./", 2739 network: request.agent.Network.CELLULAR, 2740 metered: false, 2741 roaming: true, 2742 retry: true, 2743 redirect: true, 2744 index: 0, 2745 begins: 0, 2746 ends: -1, 2747 gauge: false, 2748 precise: false, 2749 token: "it is a secret" 2750 }; 2751 let createOnCallback = (progress: request.agent.Progress) => { 2752 console.info('upload task completed.'); 2753 }; 2754 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2755 task.on('completed', createOnCallback); 2756 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2757 task.start(); 2758 }).catch((err: BusinessError) => { 2759 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2760 }); 2761 ``` 2762 2763> **NOTE** 2764> 2765> 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). 2766 2767### on('failed')<sup>10+</sup> 2768 2769on(event: 'failed', callback: (progress: [Progress](#progress10)) => void): void 2770 2771Subscribes 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. 2772 2773**Atomic service API**: This API can be used in atomic services since API version 11. 2774 2775**System capability**: SystemCapability.Request.FileTransferAgent 2776 2777**Parameters** 2778 2779| Name| Type| Mandatory| Description| 2780| -------- | -------- | -------- | -------- | 2781| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 2782| callback | function | Yes| Callback used to return the data structure of the task progress.| 2783 2784**Error codes** 2785 2786For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2787 2788| ID| Error Message| 2789| -------- | -------- | 2790| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2791 2792**Example** 2793 2794 ```ts 2795 import { BusinessError } from '@kit.BasicServicesKit'; 2796 2797 let attachments: Array<request.agent.FormItem> = [{ 2798 name: "taskOnTest", 2799 value: { 2800 filename: "taskOnTest.avi", 2801 mimeType: "application/octet-stream", 2802 path: "./taskOnTest.avi", 2803 } 2804 }]; 2805 let config: request.agent.Config = { 2806 action: request.agent.Action.UPLOAD, 2807 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2808 title: 'taskOnTest', 2809 description: 'Sample code for event listening', 2810 mode: request.agent.Mode.FOREGROUND, 2811 overwrite: false, 2812 method: "PUT", 2813 data: attachments, 2814 saveas: "./", 2815 network: request.agent.Network.CELLULAR, 2816 metered: false, 2817 roaming: true, 2818 retry: true, 2819 redirect: true, 2820 index: 0, 2821 begins: 0, 2822 ends: -1, 2823 gauge: false, 2824 precise: false, 2825 token: "it is a secret" 2826 }; 2827 let createOnCallback = (progress: request.agent.Progress) => { 2828 console.info('upload task failed.'); 2829 }; 2830 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2831 task.on('failed', createOnCallback); 2832 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2833 task.start(); 2834 }).catch((err: BusinessError) => { 2835 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2836 }); 2837 ``` 2838 2839> **NOTE** 2840> 2841> 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). 2842 2843### on('pause')<sup>11+</sup> 2844 2845on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void 2846 2847Subscribes to task pause events. This API uses an asynchronous callback to return the result. 2848 2849**System capability**: SystemCapability.Request.FileTransferAgent 2850 2851**Parameters** 2852 2853| Name| Type| Mandatory| Description| 2854| -------- | -------- | -------- | -------- | 2855| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 2856| callback | function | Yes| Callback used to return the data structure of the task progress.| 2857 2858**Error codes** 2859 2860For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2861 2862| ID| Error Message| 2863| -------- | -------- | 2864| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2865 2866**Example** 2867 2868 ```ts 2869 import { BusinessError } from '@kit.BasicServicesKit'; 2870 2871 let attachments: Array<request.agent.FormItem> = [{ 2872 name: "taskOnTest", 2873 value: { 2874 filename: "taskOnTest.avi", 2875 mimeType: "application/octet-stream", 2876 path: "./taskOnTest.avi", 2877 } 2878 }]; 2879 let config: request.agent.Config = { 2880 action: request.agent.Action.UPLOAD, 2881 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2882 title: 'taskOnTest', 2883 description: 'Sample code for event listening', 2884 mode: request.agent.Mode.FOREGROUND, 2885 overwrite: false, 2886 method: "PUT", 2887 data: attachments, 2888 saveas: "./", 2889 network: request.agent.Network.CELLULAR, 2890 metered: false, 2891 roaming: true, 2892 retry: true, 2893 redirect: true, 2894 index: 0, 2895 begins: 0, 2896 ends: -1, 2897 gauge: false, 2898 precise: false, 2899 token: "it is a secret" 2900 }; 2901 let createOnCallback = (progress: request.agent.Progress) => { 2902 console.info('upload task pause.'); 2903 }; 2904 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2905 task.on('pause', createOnCallback); 2906 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2907 task.start(); 2908 }).catch((err: BusinessError) => { 2909 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2910 }); 2911 ``` 2912 2913> **NOTE** 2914> 2915> 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). 2916 2917### on('resume')<sup>11+</sup> 2918 2919on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void 2920 2921Subscribes to task resume events. This API uses an asynchronous callback to return the result. 2922 2923**System capability**: SystemCapability.Request.FileTransferAgent 2924 2925**Parameters** 2926 2927| Name| Type| Mandatory| Description| 2928| -------- | -------- | -------- | -------- | 2929| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 2930| callback | function | Yes| Callback used to return the data structure of the task progress.| 2931 2932**Error codes** 2933 2934For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2935 2936| ID| Error Message| 2937| -------- | -------- | 2938| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2939 2940**Example** 2941 2942 ```ts 2943 import { BusinessError } from '@kit.BasicServicesKit'; 2944 2945 let attachments: Array<request.agent.FormItem> = [{ 2946 name: "taskOnTest", 2947 value: { 2948 filename: "taskOnTest.avi", 2949 mimeType: "application/octet-stream", 2950 path: "./taskOnTest.avi", 2951 } 2952 }]; 2953 let config: request.agent.Config = { 2954 action: request.agent.Action.UPLOAD, 2955 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2956 title: 'taskOnTest', 2957 description: 'Sample code for event listening', 2958 mode: request.agent.Mode.FOREGROUND, 2959 overwrite: false, 2960 method: "PUT", 2961 data: attachments, 2962 saveas: "./", 2963 network: request.agent.Network.CELLULAR, 2964 metered: false, 2965 roaming: true, 2966 retry: true, 2967 redirect: true, 2968 index: 0, 2969 begins: 0, 2970 ends: -1, 2971 gauge: false, 2972 precise: false, 2973 token: "it is a secret" 2974 }; 2975 let createOnCallback = (progress: request.agent.Progress) => { 2976 console.info('upload task resume.'); 2977 }; 2978 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2979 task.on('resume', createOnCallback); 2980 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2981 task.start(); 2982 }).catch((err: BusinessError) => { 2983 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2984 }); 2985 ``` 2986 2987> **NOTE** 2988> 2989> 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). 2990 2991### on('remove')<sup>11+</sup> 2992 2993on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void 2994 2995Subscribes to task removal events. This API uses an asynchronous callback to return the result. 2996 2997**System capability**: SystemCapability.Request.FileTransferAgent 2998 2999**Parameters** 3000 3001| Name| Type| Mandatory| Description| 3002| -------- | -------- | -------- | -------- | 3003| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 3004| callback | function | Yes| Callback used to return the data structure of the task progress.| 3005 3006**Error codes** 3007 3008For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3009 3010| ID| Error Message| 3011| -------- | -------- | 3012| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3013 3014**Example** 3015 3016 ```ts 3017 import { BusinessError } from '@kit.BasicServicesKit'; 3018 3019 let attachments: Array<request.agent.FormItem> = [{ 3020 name: "taskOnTest", 3021 value: { 3022 filename: "taskOnTest.avi", 3023 mimeType: "application/octet-stream", 3024 path: "./taskOnTest.avi", 3025 } 3026 }]; 3027 let config: request.agent.Config = { 3028 action: request.agent.Action.UPLOAD, 3029 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3030 title: 'taskOnTest', 3031 description: 'Sample code for event listening', 3032 mode: request.agent.Mode.FOREGROUND, 3033 overwrite: false, 3034 method: "PUT", 3035 data: attachments, 3036 saveas: "./", 3037 network: request.agent.Network.CELLULAR, 3038 metered: false, 3039 roaming: true, 3040 retry: true, 3041 redirect: true, 3042 index: 0, 3043 begins: 0, 3044 ends: -1, 3045 gauge: false, 3046 precise: false, 3047 token: "it is a secret" 3048 }; 3049 let createOnCallback = (progress: request.agent.Progress) => { 3050 console.info('upload task remove.'); 3051 }; 3052 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3053 task.on('remove', createOnCallback); 3054 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3055 task.start(); 3056 }).catch((err: BusinessError) => { 3057 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3058 }); 3059 ``` 3060 3061> **NOTE** 3062> 3063> 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). 3064 3065### on('response')<sup>12+</sup> 3066 3067on(event: 'response', callback: Callback<HttpResponse>): void 3068 3069Subscribes to task response headers. This API uses an asynchronous callback to return the result. 3070 3071**Atomic service API**: This API can be used in atomic services since API version 12. 3072 3073**System capability**: SystemCapability.Request.FileTransferAgent 3074 3075**Parameters** 3076 3077| Name| Type| Mandatory| Description| 3078| -------- | -------- | -------- | -------- | 3079| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3080| callback | function | Yes| Callback used to return the data structure of the task response header.| 3081 3082**Error codes** 3083 3084For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3085 3086| ID| Error Message| 3087| -------- | -------- | 3088| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3089 3090**Example** 3091 3092 ```ts 3093 import { BusinessError } from '@kit.BasicServicesKit'; 3094 3095 let attachments: Array<request.agent.FormItem> = [{ 3096 name: "taskOnTest", 3097 value: { 3098 filename: "taskOnTest.avi", 3099 mimeType: "application/octet-stream", 3100 path: "./taskOnTest.avi", 3101 } 3102 }]; 3103 let config: request.agent.Config = { 3104 action: request.agent.Action.UPLOAD, 3105 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3106 title: 'taskOnTest', 3107 description: 'Sample code for event listening', 3108 mode: request.agent.Mode.FOREGROUND, 3109 overwrite: false, 3110 method: "PUT", 3111 data: attachments, 3112 saveas: "./", 3113 network: request.agent.Network.CELLULAR, 3114 metered: false, 3115 roaming: true, 3116 retry: true, 3117 redirect: true, 3118 index: 0, 3119 begins: 0, 3120 ends: -1, 3121 gauge: false, 3122 precise: false, 3123 token: "it is a secret" 3124 }; 3125 let createOnCallback = (response: request.agent.HttpResponse) => { 3126 console.info('upload task response.'); 3127 }; 3128 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3129 task.on('response', createOnCallback); 3130 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3131 task.start(); 3132 }).catch((err: BusinessError) => { 3133 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3134 }); 3135 ``` 3136 3137> **NOTE** 3138> 3139> 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). 3140 3141### off('progress')<sup>10+</sup> 3142 3143off(event: 'progress', callback?: (progress: [Progress](#progress10)) => void): void 3144 3145Unsubscribes from task progress events. 3146 3147**Atomic service API**: This API can be used in atomic services since API version 11. 3148 3149**System capability**: SystemCapability.Request.FileTransferAgent 3150 3151**Parameters** 3152 3153| Name| Type| Mandatory| Description| 3154| -------- | -------- | -------- | -------- | 3155| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 3156| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3157 3158**Error codes** 3159 3160For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3161 3162| ID| Error Message| 3163| -------- | -------- | 3164| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3165 3166**Example** 3167 3168 ```ts 3169 import { BusinessError } from '@kit.BasicServicesKit'; 3170 3171 let attachments: Array<request.agent.FormItem> = [{ 3172 name: "taskOffTest", 3173 value: { 3174 filename: "taskOffTest.avi", 3175 mimeType: "application/octet-stream", 3176 path: "./taskOffTest.avi", 3177 } 3178 }]; 3179 let config: request.agent.Config = { 3180 action: request.agent.Action.UPLOAD, 3181 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3182 title: 'taskOffTest', 3183 description: 'Sample code for event listening', 3184 mode: request.agent.Mode.FOREGROUND, 3185 overwrite: false, 3186 method: "PUT", 3187 data: attachments, 3188 saveas: "./", 3189 network: request.agent.Network.CELLULAR, 3190 metered: false, 3191 roaming: true, 3192 retry: true, 3193 redirect: true, 3194 index: 0, 3195 begins: 0, 3196 ends: -1, 3197 gauge: false, 3198 precise: false, 3199 token: "it is a secret" 3200 }; 3201 let createOffCallback1 = (progress: request.agent.Progress) => { 3202 console.info('upload task progress.'); 3203 }; 3204 let createOffCallback2 = (progress: request.agent.Progress) => { 3205 console.info('upload task progress.'); 3206 }; 3207 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3208 task.on('progress', createOffCallback1); 3209 task.on('progress', createOffCallback2); 3210 // Unsubscribe from createOffCallback1. 3211 task.off('progress', createOffCallback1); 3212 // Unsubscribe from all callbacks of task progress changes. 3213 task.off('progress'); 3214 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3215 task.start(); 3216 }).catch((err: BusinessError) => { 3217 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3218 }); 3219 ``` 3220 3221> **NOTE** 3222> 3223> 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). 3224 3225### off('completed')<sup>10+</sup> 3226 3227off(event: 'completed', callback?: (progress: [Progress](#progress10)) => void): void 3228 3229Unsubscribes from task completion events. 3230 3231**Atomic service API**: This API can be used in atomic services since API version 11. 3232 3233**System capability**: SystemCapability.Request.FileTransferAgent 3234 3235**Parameters** 3236 3237| Name| Type| Mandatory| Description| 3238| -------- | -------- | -------- | -------- | 3239| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 3240| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3241 3242**Error codes** 3243 3244For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3245 3246| ID| Error Message| 3247| -------- | -------- | 3248| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3249 3250**Example** 3251 3252 ```ts 3253 import { BusinessError } from '@kit.BasicServicesKit'; 3254 3255 let attachments: Array<request.agent.FormItem> = [{ 3256 name: "taskOffTest", 3257 value: { 3258 filename: "taskOffTest.avi", 3259 mimeType: "application/octet-stream", 3260 path: "./taskOffTest.avi", 3261 } 3262 }]; 3263 let config: request.agent.Config = { 3264 action: request.agent.Action.UPLOAD, 3265 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3266 title: 'taskOffTest', 3267 description: 'Sample code for event listening', 3268 mode: request.agent.Mode.FOREGROUND, 3269 overwrite: false, 3270 method: "PUT", 3271 data: attachments, 3272 saveas: "./", 3273 network: request.agent.Network.CELLULAR, 3274 metered: false, 3275 roaming: true, 3276 retry: true, 3277 redirect: true, 3278 index: 0, 3279 begins: 0, 3280 ends: -1, 3281 gauge: false, 3282 precise: false, 3283 token: "it is a secret" 3284 }; 3285 let createOffCallback1 = (progress: request.agent.Progress) => { 3286 console.info('upload task completed.'); 3287 }; 3288 let createOffCallback2 = (progress: request.agent.Progress) => { 3289 console.info('upload task completed.'); 3290 }; 3291 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3292 task.on('completed', createOffCallback1); 3293 task.on('completed', createOffCallback2); 3294 // Unsubscribe from createOffCallback1. 3295 task.off('completed', createOffCallback1); 3296 // Unsubscribe from all callbacks of the task completion events. 3297 task.off('completed'); 3298 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3299 task.start(); 3300 }).catch((err: BusinessError) => { 3301 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3302 }); 3303 ``` 3304 3305> **NOTE** 3306> 3307> 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). 3308 3309### off('failed')<sup>10+</sup> 3310 3311off(event: 'failed', callback?: (progress: [Progress](#progress10)) => void): void 3312 3313Unsubscribes from task failure events. 3314 3315**Atomic service API**: This API can be used in atomic services since API version 11. 3316 3317**System capability**: SystemCapability.Request.FileTransferAgent 3318 3319**Parameters** 3320 3321| Name| Type| Mandatory| Description| 3322| -------- | -------- | -------- | -------- | 3323| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 3324| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3325 3326**Error codes** 3327 3328For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3329 3330| ID| Error Message| 3331| -------- | -------- | 3332| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3333 3334**Example** 3335 3336 ```ts 3337 import { BusinessError } from '@kit.BasicServicesKit'; 3338 3339 let attachments: Array<request.agent.FormItem> = [{ 3340 name: "taskOffTest", 3341 value: { 3342 filename: "taskOffTest.avi", 3343 mimeType: "application/octet-stream", 3344 path: "./taskOffTest.avi", 3345 } 3346 }]; 3347 let config: request.agent.Config = { 3348 action: request.agent.Action.UPLOAD, 3349 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3350 title: 'taskOffTest', 3351 description: 'Sample code for event listening', 3352 mode: request.agent.Mode.FOREGROUND, 3353 overwrite: false, 3354 method: "PUT", 3355 data: attachments, 3356 saveas: "./", 3357 network: request.agent.Network.CELLULAR, 3358 metered: false, 3359 roaming: true, 3360 retry: true, 3361 redirect: true, 3362 index: 0, 3363 begins: 0, 3364 ends: -1, 3365 gauge: false, 3366 precise: false, 3367 token: "it is a secret" 3368 }; 3369 let createOffCallback1 = (progress: request.agent.Progress) => { 3370 console.info('upload task failed.'); 3371 }; 3372 let createOffCallback2 = (progress: request.agent.Progress) => { 3373 console.info('upload task failed.'); 3374 }; 3375 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3376 task.on('failed', createOffCallback1); 3377 task.on('failed', createOffCallback2); 3378 // Unsubscribe from createOffCallback1. 3379 task.off('failed', createOffCallback1); 3380 // Unsubscribe from all callbacks of the task failure events. 3381 task.off('failed'); 3382 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3383 task.start(); 3384 }).catch((err: BusinessError) => { 3385 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3386 }); 3387 ``` 3388 3389> **NOTE** 3390> 3391> 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). 3392 3393### off('pause')<sup>11+</sup> 3394 3395off(event: 'pause', callback?: (progress: [Progress](#progress10)) => void): void 3396 3397Unsubscribes from the foreground task pause event. 3398 3399**System capability**: SystemCapability.Request.FileTransferAgent 3400 3401**Parameters** 3402 3403| Name| Type| Mandatory| Description| 3404| -------- | -------- | -------- | -------- | 3405| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 3406| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3407 3408**Error codes** 3409 3410For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3411 3412| ID| Error Message| 3413| -------- | -------- | 3414| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3415 3416**Example** 3417 3418 ```ts 3419 import { BusinessError } from '@kit.BasicServicesKit'; 3420 3421 let attachments: Array<request.agent.FormItem> = [{ 3422 name: "taskOffTest", 3423 value: { 3424 filename: "taskOffTest.avi", 3425 mimeType: "application/octet-stream", 3426 path: "./taskOffTest.avi", 3427 } 3428 }]; 3429 let config: request.agent.Config = { 3430 action: request.agent.Action.UPLOAD, 3431 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3432 title: 'taskOffTest', 3433 description: 'Sample code for event listening', 3434 mode: request.agent.Mode.FOREGROUND, 3435 overwrite: false, 3436 method: "PUT", 3437 data: attachments, 3438 saveas: "./", 3439 network: request.agent.Network.CELLULAR, 3440 metered: false, 3441 roaming: true, 3442 retry: true, 3443 redirect: true, 3444 index: 0, 3445 begins: 0, 3446 ends: -1, 3447 gauge: false, 3448 precise: false, 3449 token: "it is a secret" 3450 }; 3451 let createOffCallback1 = (progress: request.agent.Progress) => { 3452 console.info('upload task pause.'); 3453 }; 3454 let createOffCallback2 = (progress: request.agent.Progress) => { 3455 console.info('upload task pause.'); 3456 }; 3457 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3458 task.on('pause', createOffCallback1); 3459 task.on('pause', createOffCallback2); 3460 // Unsubscribe from createOffCallback1. 3461 task.off('pause', createOffCallback1); 3462 // Unsubscribe from all callbacks of the foreground task pause event. 3463 task.off('pause'); 3464 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3465 task.start(); 3466 }).catch((err: BusinessError) => { 3467 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3468 }); 3469 ``` 3470 3471> **NOTE** 3472> 3473> 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). 3474 3475### off('resume')<sup>11+</sup> 3476 3477off(event: 'resume', callback?: (progress: [Progress](#progress10)) => void): void 3478 3479Unsubscribes from the foreground task resume event. 3480 3481**System capability**: SystemCapability.Request.FileTransferAgent 3482 3483**Parameters** 3484 3485| Name| Type| Mandatory| Description| 3486| -------- | -------- | -------- | -------- | 3487| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 3488| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3489 3490**Error codes** 3491 3492For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3493 3494| ID| Error Message| 3495| -------- | -------- | 3496| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3497 3498**Example** 3499 3500 ```ts 3501 import { BusinessError } from '@kit.BasicServicesKit'; 3502 3503 let attachments: Array<request.agent.FormItem> = [{ 3504 name: "taskOffTest", 3505 value: { 3506 filename: "taskOffTest.avi", 3507 mimeType: "application/octet-stream", 3508 path: "./taskOffTest.avi", 3509 } 3510 }]; 3511 let config: request.agent.Config = { 3512 action: request.agent.Action.UPLOAD, 3513 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3514 title: 'taskOffTest', 3515 description: 'Sample code for event listening', 3516 mode: request.agent.Mode.FOREGROUND, 3517 overwrite: false, 3518 method: "PUT", 3519 data: attachments, 3520 saveas: "./", 3521 network: request.agent.Network.CELLULAR, 3522 metered: false, 3523 roaming: true, 3524 retry: true, 3525 redirect: true, 3526 index: 0, 3527 begins: 0, 3528 ends: -1, 3529 gauge: false, 3530 precise: false, 3531 token: "it is a secret" 3532 }; 3533 let createOffCallback1 = (progress: request.agent.Progress) => { 3534 console.info('upload task resume.'); 3535 }; 3536 let createOffCallback2 = (progress: request.agent.Progress) => { 3537 console.info('upload task resume.'); 3538 }; 3539 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3540 task.on('resume', createOffCallback1); 3541 task.on('resume', createOffCallback2); 3542 // Unsubscribe from createOffCallback1. 3543 task.off('resume', createOffCallback1); 3544 // Unsubscribe from all callbacks of the foreground task resume event. 3545 task.off('resume'); 3546 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3547 task.start(); 3548 }).catch((err: BusinessError) => { 3549 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3550 }); 3551 ``` 3552 3553> **NOTE** 3554> 3555> 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). 3556 3557### off('remove')<sup>11+</sup> 3558 3559off(event: 'remove', callback?: (progress: [Progress](#progress10)) => void): void 3560 3561Unsubscribes from the task removal event. 3562 3563**System capability**: SystemCapability.Request.FileTransferAgent 3564 3565**Parameters** 3566 3567| Name| Type| Mandatory| Description| 3568| -------- | -------- | -------- | -------- | 3569| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 3570| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3571 3572**Error codes** 3573 3574For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3575 3576| ID| Error Message| 3577| -------- | -------- | 3578| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3579 3580**Example** 3581 3582 ```ts 3583 import { BusinessError } from '@kit.BasicServicesKit'; 3584 3585 let attachments: Array<request.agent.FormItem> = [{ 3586 name: "taskOffTest", 3587 value: { 3588 filename: "taskOffTest.avi", 3589 mimeType: "application/octet-stream", 3590 path: "./taskOffTest.avi", 3591 } 3592 }]; 3593 let config: request.agent.Config = { 3594 action: request.agent.Action.UPLOAD, 3595 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3596 title: 'taskOffTest', 3597 description: 'Sample code for event listening', 3598 mode: request.agent.Mode.FOREGROUND, 3599 overwrite: false, 3600 method: "PUT", 3601 data: attachments, 3602 saveas: "./", 3603 network: request.agent.Network.CELLULAR, 3604 metered: false, 3605 roaming: true, 3606 retry: true, 3607 redirect: true, 3608 index: 0, 3609 begins: 0, 3610 ends: -1, 3611 gauge: false, 3612 precise: false, 3613 token: "it is a secret" 3614 }; 3615 let createOffCallback1 = (progress: request.agent.Progress) => { 3616 console.info('upload task remove.'); 3617 }; 3618 let createOffCallback2 = (progress: request.agent.Progress) => { 3619 console.info('upload task remove.'); 3620 }; 3621 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3622 task.on('remove', createOffCallback1); 3623 task.on('remove', createOffCallback2); 3624 // Unsubscribe from createOffCallback1. 3625 task.off('remove', createOffCallback1); 3626 // Unsubscribe from all callbacks of the task removal event. 3627 task.off('remove'); 3628 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3629 task.start(); 3630 }).catch((err: BusinessError) => { 3631 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3632 }); 3633 ``` 3634 3635> **NOTE** 3636> 3637> 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). 3638 3639### off('response')<sup>12+</sup> 3640 3641off(event: 'response', callback?: Callback<HttpResponse>): void 3642 3643Unsubscribes from task response headers. 3644 3645**Atomic service API**: This API can be used in atomic services since API version 12. 3646 3647**System capability**: SystemCapability.Request.FileTransferAgent 3648 3649**Parameters** 3650 3651| Name| Type| Mandatory| Description| 3652| -------- | -------- | -------- | -------- | 3653| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3654| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3655 3656**Error codes** 3657 3658For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3659 3660| ID| Error Message| 3661| -------- | -------- | 3662| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3663 3664**Example** 3665 3666 ```ts 3667 import { BusinessError } from '@kit.BasicServicesKit'; 3668 3669 let attachments: Array<request.agent.FormItem> = [{ 3670 name: "taskOffTest", 3671 value: { 3672 filename: "taskOffTest.avi", 3673 mimeType: "application/octet-stream", 3674 path: "./taskOffTest.avi", 3675 } 3676 }]; 3677 let config: request.agent.Config = { 3678 action: request.agent.Action.UPLOAD, 3679 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3680 title: 'taskOffTest', 3681 description: 'Sample code for event listening', 3682 mode: request.agent.Mode.FOREGROUND, 3683 overwrite: false, 3684 method: "PUT", 3685 data: attachments, 3686 saveas: "./", 3687 network: request.agent.Network.CELLULAR, 3688 metered: false, 3689 roaming: true, 3690 retry: true, 3691 redirect: true, 3692 index: 0, 3693 begins: 0, 3694 ends: -1, 3695 gauge: false, 3696 precise: false, 3697 token: "it is a secret" 3698 }; 3699 let createOffCallback1 = (progress: request.agent.HttpResponse) => { 3700 console.info('upload task response.'); 3701 }; 3702 let createOffCallback2 = (progress: request.agent.HttpResponse) => { 3703 console.info('upload task response.'); 3704 }; 3705 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3706 task.on('response', createOffCallback1); 3707 task.on('response', createOffCallback2); 3708 // Unsubscribe from createOffCallback1. 3709 task.off('response', createOffCallback1); 3710 // Unsubscribe from all callbacks of the task removal event. 3711 task.off('response'); 3712 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3713 task.start(); 3714 }).catch((err: BusinessError) => { 3715 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3716 }); 3717 ``` 3718 3719> **NOTE** 3720> 3721> 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). 3722 3723### start<sup>10+</sup> 3724 3725start(callback: AsyncCallback<void>): void 3726 3727Tasks in the following states can be started: 37281. Task created by **request.agent.create**. 37292. Download tasks that are created by **request.agent.create** but have failed or paused. 3730 3731**Required permissions**: ohos.permission.INTERNET 3732 3733**Atomic service API**: This API can be used in atomic services since API version 11. 3734 3735**System capability**: SystemCapability.Request.FileTransferAgent 3736 3737**Parameters** 3738 3739| Name| Type| Mandatory| Description| 3740| -------- | -------- | -------- | -------- | 3741| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3742 3743**Error codes** 3744 3745For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3746 3747| ID| Error Message| 3748| -------- | -------- | 3749| 201 | Permission denied. | 3750| 13400003 | task service ability error. | 3751| 21900007 | task state error. | 3752 3753**Example** 3754 3755 ```ts 3756 import { BusinessError } from '@kit.BasicServicesKit'; 3757 3758 let config: request.agent.Config = { 3759 action: request.agent.Action.DOWNLOAD, 3760 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3761 title: 'taskStartTest', 3762 description: 'Sample code for start the download task', 3763 mode: request.agent.Mode.BACKGROUND, 3764 overwrite: false, 3765 method: "GET", 3766 data: "", 3767 saveas: "./", 3768 network: request.agent.Network.CELLULAR, 3769 metered: false, 3770 roaming: true, 3771 retry: true, 3772 redirect: true, 3773 index: 0, 3774 begins: 0, 3775 ends: -1, 3776 gauge: false, 3777 precise: false, 3778 token: "it is a secret" 3779 }; 3780 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3781 task.start((err: BusinessError) => { 3782 if (err) { 3783 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3784 return; 3785 } 3786 console.info(`Succeeded in starting a download task.`); 3787 }); 3788 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3789 }).catch((err: BusinessError) => { 3790 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3791 }); 3792 ``` 3793 3794> **NOTE** 3795> 3796> 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). 3797 3798### start<sup>10+</sup> 3799 3800start(): Promise<void> 3801 3802Tasks in the following states can be started: 38031. Task created by **request.agent.create**. 38042. Download tasks that are created by **request.agent.create** but have failed or paused. 3805 3806**Required permissions**: ohos.permission.INTERNET 3807 3808**Atomic service API**: This API can be used in atomic services since API version 11. 3809 3810**System capability**: SystemCapability.Request.FileTransferAgent 3811 3812**Return value** 3813 3814| Type | Description | 3815| ------------------- | ------------------------- | 3816| Promise<void> | Promise that returns no value.| 3817 3818**Error codes** 3819 3820For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3821 3822| ID| Error Message| 3823| -------- | -------- | 3824| 201 | Permission denied. | 3825| 13400003 | task service ability error. | 3826| 21900007 | task state error. | 3827 3828**Example** 3829 3830 ```ts 3831 import { BusinessError } from '@kit.BasicServicesKit'; 3832 3833 let config: request.agent.Config = { 3834 action: request.agent.Action.DOWNLOAD, 3835 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3836 title: 'taskStartTest', 3837 description: 'Sample code for start the download task', 3838 mode: request.agent.Mode.BACKGROUND, 3839 overwrite: false, 3840 method: "GET", 3841 data: "", 3842 saveas: "./", 3843 network: request.agent.Network.CELLULAR, 3844 metered: false, 3845 roaming: true, 3846 retry: true, 3847 redirect: true, 3848 index: 0, 3849 begins: 0, 3850 ends: -1, 3851 gauge: false, 3852 precise: false, 3853 token: "it is a secret" 3854 }; 3855 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3856 task.start().then(() => { 3857 console.info(`Succeeded in starting a download task.`); 3858 }).catch((err: BusinessError) => { 3859 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3860 }); 3861 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3862 }).catch((err: BusinessError) => { 3863 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3864 }); 3865 ``` 3866 3867> **NOTE** 3868> 3869> 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). 3870 3871### pause<sup>10+</sup> 3872 3873pause(callback: AsyncCallback<void>): void 3874 3875Pauses a task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result. 3876 3877**System capability**: SystemCapability.Request.FileTransferAgent 3878 3879**Parameters** 3880 3881| Name| Type| Mandatory| Description| 3882| -------- | -------- | -------- | -------- | 3883| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3884 3885**Error codes** 3886 3887For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3888 3889| ID| Error Message| 3890| -------- | -------- | 3891| 13400003 | task service ability error. | 3892| 21900007 | task state error. | 3893 3894**Example** 3895 3896 ```ts 3897 import { BusinessError } from '@kit.BasicServicesKit'; 3898 3899 let config: request.agent.Config = { 3900 action: request.agent.Action.DOWNLOAD, 3901 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3902 title: 'taskPauseTest', 3903 description: 'Sample code for pause the download task', 3904 mode: request.agent.Mode.BACKGROUND, 3905 overwrite: false, 3906 method: "GET", 3907 data: "", 3908 saveas: "./", 3909 network: request.agent.Network.CELLULAR, 3910 metered: false, 3911 roaming: true, 3912 retry: true, 3913 redirect: true, 3914 index: 0, 3915 begins: 0, 3916 ends: -1, 3917 gauge: false, 3918 precise: false, 3919 token: "it is a secret" 3920 }; 3921 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3922 task.start(); 3923 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3924 task.pause((err: BusinessError) => { 3925 if (err) { 3926 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3927 return; 3928 } 3929 console.info(`Succeeded in pausing a download task. `); 3930 }); 3931 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3932 }).catch((err: BusinessError) => { 3933 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3934 }); 3935 ``` 3936 3937### pause<sup>10+</sup> 3938 3939pause(): Promise<void> 3940 3941Pauses a task that is waiting, running, or retrying. This API uses a promise to return the result. 3942 3943**System capability**: SystemCapability.Request.FileTransferAgent 3944 3945**Return value** 3946 3947| Type | Description | 3948| ------------------- | ------------------------- | 3949| Promise<void> | Promise that returns no value.| 3950 3951**Error codes** 3952 3953For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3954 3955| ID| Error Message| 3956| -------- | -------- | 3957| 13400003 | task service ability error. | 3958| 21900007 | task state error. | 3959 3960**Example** 3961 3962 ```ts 3963 import { BusinessError } from '@kit.BasicServicesKit'; 3964 3965 let config: request.agent.Config = { 3966 action: request.agent.Action.DOWNLOAD, 3967 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3968 title: 'taskPauseTest', 3969 description: 'Sample code for pause the download task', 3970 mode: request.agent.Mode.BACKGROUND, 3971 overwrite: false, 3972 method: "GET", 3973 data: "", 3974 saveas: "./", 3975 network: request.agent.Network.CELLULAR, 3976 metered: false, 3977 roaming: true, 3978 retry: true, 3979 redirect: true, 3980 index: 0, 3981 begins: 0, 3982 ends: -1, 3983 gauge: false, 3984 precise: false, 3985 token: "it is a secret" 3986 }; 3987 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3988 task.start(); 3989 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3990 task.pause().then(() => { 3991 console.info(`Succeeded in pausing a download task. `); 3992 }).catch((err: BusinessError) => { 3993 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3994 }); 3995 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3996 }).catch((err: BusinessError) => { 3997 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3998 }); 3999 ``` 4000 4001### resume<sup>10+</sup> 4002 4003resume(callback: AsyncCallback<void>): void 4004 4005Resumes a paused task. This API uses an asynchronous callback to return the result. 4006 4007**Required permissions**: ohos.permission.INTERNET 4008 4009**System capability**: SystemCapability.Request.FileTransferAgent 4010 4011**Parameters** 4012 4013| Name| Type| Mandatory| Description| 4014| -------- | -------- | -------- | -------- | 4015| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4016 4017**Error codes** 4018 4019For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4020 4021| ID| Error Message| 4022| -------- | -------- | 4023| 201 | Permission denied. | 4024| 13400003 | task service ability error. | 4025| 21900007 | task state error. | 4026 4027**Example** 4028 4029 ```ts 4030 import { BusinessError } from '@kit.BasicServicesKit'; 4031 4032 let config: request.agent.Config = { 4033 action: request.agent.Action.DOWNLOAD, 4034 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4035 title: 'taskResumeTest', 4036 description: 'Sample code for resume the download task', 4037 mode: request.agent.Mode.BACKGROUND, 4038 overwrite: false, 4039 method: "GET", 4040 data: "", 4041 saveas: "./", 4042 network: request.agent.Network.CELLULAR, 4043 metered: false, 4044 roaming: true, 4045 retry: true, 4046 redirect: true, 4047 index: 0, 4048 begins: 0, 4049 ends: -1, 4050 gauge: false, 4051 precise: false, 4052 token: "it is a secret" 4053 }; 4054 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4055 task.start(); 4056 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4057 task.pause(); 4058 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4059 task.resume((err: BusinessError) => { 4060 if (err) { 4061 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4062 return; 4063 } 4064 console.info(`Succeeded in resuming a download task. `); 4065 }); 4066 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4067 }).catch((err: BusinessError) => { 4068 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4069 }); 4070 ``` 4071 4072### resume<sup>10+</sup> 4073 4074resume(): Promise<void> 4075 4076Resumes a paused task. This API uses a promise to return the result. 4077 4078**Required permissions**: ohos.permission.INTERNET 4079 4080**System capability**: SystemCapability.Request.FileTransferAgent 4081 4082**Return value** 4083 4084| Type | Description | 4085| ------------------- | ------------------------- | 4086| Promise<void> | Promise that returns no value.| 4087 4088**Error codes** 4089 4090For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4091 4092| ID| Error Message| 4093| -------- | -------- | 4094| 201 | Permission denied. | 4095| 13400003 | task service ability error. | 4096| 21900007 | task state error. | 4097 4098**Example** 4099 4100 ```ts 4101 import { BusinessError } from '@kit.BasicServicesKit'; 4102 4103 let config: request.agent.Config = { 4104 action: request.agent.Action.DOWNLOAD, 4105 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4106 title: 'taskResumeTest', 4107 description: 'Sample code for resume the download task', 4108 mode: request.agent.Mode.BACKGROUND, 4109 overwrite: false, 4110 method: "GET", 4111 data: "", 4112 saveas: "./", 4113 network: request.agent.Network.CELLULAR, 4114 metered: false, 4115 roaming: true, 4116 retry: true, 4117 redirect: true, 4118 index: 0, 4119 begins: 0, 4120 ends: -1, 4121 gauge: false, 4122 precise: false, 4123 token: "it is a secret" 4124 }; 4125 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4126 task.start(); 4127 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4128 task.pause(); 4129 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4130 task.resume().then(() => { 4131 console.info(`Succeeded in resuming a download task. `); 4132 }).catch((err: BusinessError) => { 4133 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4134 }); 4135 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4136 }).catch((err: BusinessError) => { 4137 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4138 }); 4139 ``` 4140 4141### stop<sup>10+</sup> 4142 4143stop(callback: AsyncCallback<void>): void 4144 4145Stops 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. 4146 4147**Atomic service API**: This API can be used in atomic services since API version 11. 4148 4149**System capability**: SystemCapability.Request.FileTransferAgent 4150 4151**Parameters** 4152 4153| Name| Type| Mandatory| Description| 4154| -------- | -------- | -------- | -------- | 4155| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4156 4157**Error codes** 4158 4159For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4160 4161| ID| Error Message| 4162| -------- | -------- | 4163| 13400003 | task service ability error. | 4164| 21900007 | task state error. | 4165 4166**Example** 4167 4168 ```ts 4169 import { BusinessError } from '@kit.BasicServicesKit'; 4170 4171 let config: request.agent.Config = { 4172 action: request.agent.Action.DOWNLOAD, 4173 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4174 title: 'taskStopTest', 4175 description: 'Sample code for stop the download task', 4176 mode: request.agent.Mode.BACKGROUND, 4177 overwrite: false, 4178 method: "GET", 4179 data: "", 4180 saveas: "./", 4181 network: request.agent.Network.CELLULAR, 4182 metered: false, 4183 roaming: true, 4184 retry: true, 4185 redirect: true, 4186 index: 0, 4187 begins: 0, 4188 ends: -1, 4189 gauge: false, 4190 precise: false, 4191 token: "it is a secret" 4192 }; 4193 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4194 task.start(); 4195 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4196 task.stop((err: BusinessError) => { 4197 if (err) { 4198 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4199 return; 4200 } 4201 console.info(`Succeeded in stopping a download task. `); 4202 }); 4203 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4204 }).catch((err: BusinessError) => { 4205 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4206 }); 4207 ``` 4208 4209 4210### stop<sup>10+</sup> 4211 4212stop(): Promise<void> 4213 4214Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. 4215 4216**Atomic service API**: This API can be used in atomic services since API version 11. 4217 4218**System capability**: SystemCapability.Request.FileTransferAgent 4219 4220**Return value** 4221 4222| Type | Description | 4223| ------------------- | ------------------------- | 4224| Promise<void> | Promise that returns no value.| 4225 4226**Error codes** 4227 4228For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4229 4230| ID| Error Message| 4231| -------- | -------- | 4232| 13400003 | task service ability error. | 4233| 21900007 | task state error. | 4234 4235**Example** 4236 4237 ```ts 4238 import { BusinessError } from '@kit.BasicServicesKit'; 4239 4240 let config: request.agent.Config = { 4241 action: request.agent.Action.DOWNLOAD, 4242 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4243 title: 'taskStopTest', 4244 description: 'Sample code for stop the download task', 4245 mode: request.agent.Mode.BACKGROUND, 4246 overwrite: false, 4247 method: "GET", 4248 data: "", 4249 saveas: "./", 4250 network: request.agent.Network.CELLULAR, 4251 metered: false, 4252 roaming: true, 4253 retry: true, 4254 redirect: true, 4255 index: 0, 4256 begins: 0, 4257 ends: -1, 4258 gauge: false, 4259 precise: false, 4260 token: "it is a secret" 4261 }; 4262 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4263 task.start(); 4264 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4265 task.stop().then(() => { 4266 console.info(`Succeeded in stopping a download task. `); 4267 }).catch((err: BusinessError) => { 4268 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4269 }); 4270 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4271 }).catch((err: BusinessError) => { 4272 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4273 }); 4274 ``` 4275 4276## request.agent.create<sup>10+</sup> 4277 4278create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void 4279 4280Creates an upload or download task and adds it to the queue. This API uses an asynchronous callback to return a result. HTTP is supported. 4281 4282 4283**Required permissions**: ohos.permission.INTERNET 4284 4285**Atomic service API**: This API can be used in atomic services since API version 11. 4286 4287**System capability**: SystemCapability.Request.FileTransferAgent 4288 4289**Parameters** 4290 4291| Name| Type| Mandatory| Description| 4292| -------- | -------- | -------- | -------- | 4293| config | [Config](#config10) | Yes| Task configuration.| 4294| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4295| 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.| 4296 4297**Error codes** 4298 4299For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4300 4301| ID| Error Message| 4302| -------- | -------- | 4303| 201 | permission denied. | 4304| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4305| 13400001 | file operation error. | 4306| 13400003 | task service ability error. | 4307| 21900004 | the application task queue is full. | 4308| 21900005 | task mode error. | 4309 4310**Example** 4311 4312 ```ts 4313 import { BusinessError } from '@kit.BasicServicesKit'; 4314 4315 let attachments: Array<request.agent.FormItem> = [{ 4316 name: "createTest", 4317 value: { 4318 filename: "createTest.avi", 4319 mimeType: "application/octet-stream", 4320 path: "./createTest.avi", 4321 } 4322 }]; 4323 let config: request.agent.Config = { 4324 action: request.agent.Action.UPLOAD, 4325 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4326 title: 'createTest', 4327 description: 'Sample code for create task', 4328 mode: request.agent.Mode.BACKGROUND, 4329 overwrite: false, 4330 method: "PUT", 4331 data: attachments, 4332 saveas: "./", 4333 network: request.agent.Network.CELLULAR, 4334 metered: false, 4335 roaming: true, 4336 retry: true, 4337 redirect: true, 4338 index: 0, 4339 begins: 0, 4340 ends: -1, 4341 gauge: false, 4342 precise: false, 4343 token: "it is a secret" 4344 }; 4345 request.agent.create(getContext(), config, async (err: BusinessError, task: request.agent.Task) => { 4346 if (err) { 4347 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4348 return; 4349 } 4350 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4351 await task.start(); 4352 // You need to manually call remove() to end the lifecycle of the task object. 4353 request.agent.remove(task.tid); 4354 }); 4355 ``` 4356 4357> **NOTE** 4358> 4359> 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). 4360 4361## request.agent.create<sup>10+</sup> 4362 4363create(context: BaseContext, config: Config): Promise<Task> 4364 4365Creates an upload or download task and adds it to the queue. This API uses a promise to return the result. HTTP is supported. 4366 4367 4368**Required permissions**: ohos.permission.INTERNET 4369 4370**Atomic service API**: This API can be used in atomic services since API version 11. 4371 4372**System capability**: SystemCapability.Request.FileTransferAgent 4373 4374**Parameters** 4375 4376| Name| Type| Mandatory| Description| 4377| -------- | -------- | -------- | -------- | 4378| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4379| config | [Config](#config10) | Yes| Task configuration.| 4380 4381**Return value** 4382 4383| Type | Description | 4384| ------------------- | ------------------------- | 4385| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4386 4387**Error codes** 4388 4389For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4390 4391| ID| Error Message| 4392| -------- | -------- | 4393| 201 | permission denied. | 4394| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4395| 13400001 | file operation error. | 4396| 13400003 | task service ability error. | 4397| 21900004 | the application task queue is full. | 4398| 21900005 | task mode error. | 4399 4400**Example** 4401 4402 ```ts 4403 import { BusinessError } from '@kit.BasicServicesKit'; 4404 4405 let attachments: Array<request.agent.FormItem> = [{ 4406 name: "createTest", 4407 value: { 4408 filename: "createTest.avi", 4409 mimeType: "application/octet-stream", 4410 path: "./createTest.avi", 4411 } 4412 }]; 4413 let config: request.agent.Config = { 4414 action: request.agent.Action.UPLOAD, 4415 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4416 title: 'createTest', 4417 description: 'Sample code for create task', 4418 mode: request.agent.Mode.BACKGROUND, 4419 overwrite: false, 4420 method: "PUT", 4421 data: attachments, 4422 saveas: "./", 4423 network: request.agent.Network.CELLULAR, 4424 metered: false, 4425 roaming: true, 4426 retry: true, 4427 redirect: true, 4428 index: 0, 4429 begins: 0, 4430 ends: -1, 4431 gauge: false, 4432 precise: false, 4433 token: "it is a secret" 4434 }; 4435 request.agent.create(getContext(), config).then(async (task: request.agent.Task) => { 4436 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4437 await task.start(); 4438 // You need to manually call remove() to end the lifecycle of the task object. 4439 request.agent.remove(task.tid); 4440 }).catch((err: BusinessError) => { 4441 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4442 }); 4443 ``` 4444 4445> **NOTE** 4446> 4447> 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). 4448 4449## request.agent.getTask<sup>11+</sup> 4450 4451getTask(context: BaseContext, id: string, token?: string): Promise<Task> 4452 4453Obtains task information based on the task ID. This API uses a promise to return the result. 4454 4455**System capability**: SystemCapability.Request.FileTransferAgent 4456 4457**Parameters** 4458 4459| Name| Type| Mandatory| Description| 4460| -------- | -------- | -------- | -------- | 4461| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4462| id | string | Yes| Task ID.| 4463| token | string | No| Token for task query.| 4464 4465**Return value** 4466 4467| Type | Description | 4468| ------------------- | ------------------------- | 4469| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4470 4471**Error codes** 4472 4473For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4474 4475| ID| Error Message| 4476| -------- | -------- | 4477| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4478| 13400003 | task service ability error. | 4479| 21900006 | task not found. | 4480 4481**Example** 4482 4483 ```ts 4484 import { BusinessError } from '@kit.BasicServicesKit'; 4485 4486 request.agent.getTask(getContext(), "123456").then((task: request.agent.Task) => { 4487 console.info(`Succeeded in querying a task. result: ${task.tid}`); 4488 }).catch((err: BusinessError) => { 4489 console.error(`Failed to query a task, Code: ${err.code}, message: ${err.message}`); 4490 }); 4491 ``` 4492 4493## request.agent.remove<sup>10+</sup> 4494 4495remove(id: string, callback: AsyncCallback<void>): void 4496 4497Removes 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. 4498 4499**Atomic service API**: This API can be used in atomic services since API version 11. 4500 4501**System capability**: SystemCapability.Request.FileTransferAgent 4502 4503**Parameters** 4504 4505| Name| Type| Mandatory| Description| 4506| -------- | -------- | -------- | -------- | 4507| id | string | Yes| Task ID.| 4508| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4509 4510**Error codes** 4511 4512For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4513 4514| ID| Error Message| 4515| -------- | -------- | 4516| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4517| 13400003 | task service ability error. | 4518| 21900006 | task not found. | 4519 4520**Example** 4521 4522 ```ts 4523 import { BusinessError } from '@kit.BasicServicesKit'; 4524 4525 request.agent.remove("123456", (err: BusinessError) => { 4526 if (err) { 4527 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4528 return; 4529 } 4530 console.info(`Succeeded in creating a download task.`); 4531 }); 4532 ``` 4533 4534 4535## request.agent.remove<sup>10+</sup> 4536 4537remove(id: string): Promise<void> 4538 4539Removes 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. 4540 4541**Atomic service API**: This API can be used in atomic services since API version 11. 4542 4543**System capability**: SystemCapability.Request.FileTransferAgent 4544 4545**Parameters** 4546 4547| Name| Type| Mandatory| Description| 4548| -------- | -------- | -------- | -------- | 4549| id | string | Yes| Task ID.| 4550 4551**Return value** 4552 4553| Type | Description | 4554| ------------------- | ------------------------- | 4555| Promise<void> | Promise that returns no value.| 4556 4557**Error codes** 4558 4559For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4560 4561| ID| Error Message| 4562| -------- | -------- | 4563| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4564| 13400003 | task service ability error. | 4565| 21900006 | task not found. | 4566 4567**Example** 4568 4569 ```ts 4570 import { BusinessError } from '@kit.BasicServicesKit'; 4571 4572 request.agent.remove("123456").then(() => { 4573 console.info(`Succeeded in removing a download task. `); 4574 }).catch((err: BusinessError) => { 4575 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4576 }); 4577 ``` 4578 4579 4580## request.agent.show<sup>10+</sup> 4581 4582show(id: string, callback: AsyncCallback<TaskInfo>): void 4583 4584Queries a task details based on the task ID. This API uses an asynchronous callback to return the result. 4585 4586**System capability**: SystemCapability.Request.FileTransferAgent 4587 4588**Parameters** 4589 4590| Name| Type| Mandatory| Description| 4591| -------- | -------- | -------- | -------- | 4592| id | string | Yes| Task ID.| 4593| 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.| 4594 4595**Error codes** 4596 4597For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4598 4599| ID| Error Message| 4600| -------- | -------- | 4601| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4602| 13400003 | task service ability error. | 4603| 21900006 | task not found. | 4604 4605**Example** 4606 4607 ```ts 4608 import { BusinessError } from '@kit.BasicServicesKit'; 4609 4610 request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4611 if (err) { 4612 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4613 return; 4614 } 4615 console.info(`Succeeded in showing a upload task.`); 4616 }); 4617 ``` 4618 4619 4620## request.agent.show<sup>10+</sup> 4621 4622show(id: string): Promise<TaskInfo> 4623 4624Queries a task details based on the task ID. This API uses a promise to return the result. 4625 4626**System capability**: SystemCapability.Request.FileTransferAgent 4627 4628**Parameters** 4629 4630| Name| Type| Mandatory| Description| 4631| -------- | -------- | -------- | -------- | 4632| id | string | Yes| Task ID.| 4633 4634**Return value** 4635 4636| Type | Description | 4637| ------------------- | ------------------------- | 4638| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4639 4640**Error codes** 4641 4642For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4643 4644| ID| Error Message| 4645| -------- | -------- | 4646| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4647| 13400003 | task service ability error. | 4648| 21900006 | task not found. | 4649 4650**Example** 4651 4652 ```ts 4653 import { BusinessError } from '@kit.BasicServicesKit'; 4654 4655 request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => { 4656 console.info(`Succeeded in showing a upload task.`); 4657 }).catch((err: BusinessError) => { 4658 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4659 }); 4660 ``` 4661 4662 4663## request.agent.touch<sup>10+</sup> 4664 4665touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void 4666 4667Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result. 4668 4669**System capability**: SystemCapability.Request.FileTransferAgent 4670 4671**Parameters** 4672 4673| Name| Type| Mandatory| Description| 4674| -------- | -------- | -------- | -------- | 4675| id | string | Yes| Task ID.| 4676| token | string | Yes| Token for task query.| 4677| 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.| 4678 4679**Error codes** 4680 4681For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4682 4683| ID| Error Message| 4684| -------- | -------- | 4685| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4686| 13400003 | task service ability error. | 4687| 21900006 | task not found. | 4688 4689**Example** 4690 4691 ```ts 4692 import { BusinessError } from '@kit.BasicServicesKit'; 4693 4694 request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4695 if (err) { 4696 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4697 return; 4698 } 4699 console.info(`Succeeded in touching a upload task.`); 4700 }); 4701 ``` 4702 4703 4704## request.agent.touch<sup>10+</sup> 4705 4706touch(id: string, token: string): Promise<TaskInfo> 4707 4708Queries the task details based on the task ID and token. This API uses a promise to return the result. 4709 4710**System capability**: SystemCapability.Request.FileTransferAgent 4711 4712**Parameters** 4713 4714| Name| Type| Mandatory| Description| 4715| -------- | -------- | -------- | -------- | 4716| id | string | Yes| Task ID.| 4717| token | string | Yes| Token for task query.| 4718 4719**Return value** 4720 4721| Type | Description | 4722| ------------------- | ------------------------- | 4723| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4724 4725**Error codes** 4726 4727For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4728 4729| ID| Error Message| 4730| -------- | -------- | 4731| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4732| 13400003 | task service ability error. | 4733| 21900006 | task not found. | 4734 4735**Example** 4736 4737 ```ts 4738 import { BusinessError } from '@kit.BasicServicesKit'; 4739 4740 request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { 4741 console.info(`Succeeded in touching a upload task. `); 4742 }).catch((err: BusinessError) => { 4743 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4744 }); 4745 ``` 4746 4747## request.agent.search<sup>10+</sup> 4748 4749search(callback: AsyncCallback<Array<string>>): void 4750 4751Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4752 4753**System capability**: SystemCapability.Request.FileTransferAgent 4754 4755**Parameters** 4756 4757| Name| Type| Mandatory| Description| 4758| -------- | -------- | -------- | -------- | 4759| 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.| 4760 4761**Error codes** 4762 4763For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4764 4765| ID| Error Message| 4766| -------- | -------- | 4767| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4768| 13400003 | task service ability error. | 4769 4770**Example** 4771 4772 ```ts 4773 import { BusinessError } from '@kit.BasicServicesKit'; 4774 4775 request.agent.search((err: BusinessError, data: Array<string>) => { 4776 if (err) { 4777 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4778 return; 4779 } 4780 console.info(`Succeeded in searching a upload task. `); 4781 }); 4782 ``` 4783 4784## request.agent.search<sup>10+</sup> 4785 4786search(filter: Filter, callback: AsyncCallback<Array<string>>): void 4787 4788Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4789 4790**System capability**: SystemCapability.Request.FileTransferAgent 4791 4792**Parameters** 4793 4794| Name| Type| Mandatory| Description| 4795| -------- | -------- | -------- | -------- | 4796| filter | [Filter](#filter10) | Yes| Filter criteria.| 4797| 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.| 4798 4799**Error codes** 4800 4801For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4802 4803| ID| Error Message| 4804| -------- | -------- | 4805| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4806| 13400003 | task service ability error. | 4807 4808**Example** 4809 4810 ```ts 4811 import { BusinessError } from '@kit.BasicServicesKit'; 4812 4813 let filter: request.agent.Filter = { 4814 action: request.agent.Action.UPLOAD, 4815 mode: request.agent.Mode.BACKGROUND 4816 } 4817 request.agent.search(filter, (err: BusinessError, data: Array<string>) => { 4818 if (err) { 4819 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4820 return; 4821 } 4822 console.info(`Succeeded in searching a upload task. `); 4823 }); 4824 ``` 4825 4826 4827## request.agent.search<sup>10+</sup> 4828 4829search(filter?: Filter): Promise<Array<string>> 4830 4831Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. 4832 4833**System capability**: SystemCapability.Request.FileTransferAgent 4834 4835**Parameters** 4836 4837| Name| Type| Mandatory| Description| 4838| -------- | -------- | -------- | -------- | 4839| filter | [Filter](#filter10) | No| Filter criteria.| 4840 4841**Return value** 4842 4843| Type | Description | 4844| ------------------- | ------------------------- | 4845| Promise<Array<string>> | Promise Promise used to return task ID matches.| 4846 4847**Error codes** 4848 4849For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4850 4851| ID| Error Message| 4852| -------- | -------- | 4853| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4854| 13400003 | task service ability error. | 4855 4856**Example** 4857 4858 ```ts 4859 import { BusinessError } from '@kit.BasicServicesKit'; 4860 4861 let filter: request.agent.Filter = { 4862 action: request.agent.Action.UPLOAD, 4863 mode: request.agent.Mode.BACKGROUND 4864 } 4865 request.agent.search(filter).then((data: Array<string>) => { 4866 console.info(`Succeeded in searching a upload task. `); 4867 }).catch((err: BusinessError) => { 4868 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4869 }); 4870 ``` 4871 4872## request.agent.createGroup<sup>15+</sup> 4873 4874createGroup(config: GroupConfig): Promise\<string\> 4875 4876Creates a group based on [GroupConfig<sup>15+</sup>](#groupconfig15) and returns the group ID. This API uses a promise to return the result. 4877 4878**System capability**: SystemCapability.Request.FileTransferAgent 4879 4880**Parameters** 4881 4882| Name | Type | Mandatory| Description | 4883|--------|---------------------------------------------|----|-----------| 4884| config | [GroupConfig<sup>15+</sup>](#groupconfig15) | Yes | Group options for a download task.| 4885 4886**Return value** 4887 4888| Type | Description | 4889|-------------------|----------------------------------| 4890| Promise\<string\> | Promise used to return the result.| 4891 4892**Error codes** 4893 4894For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4895 4896| ID | Error Message | 4897|----------|------------------------------------------------------------------------------------------------| 4898| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4899| 13400003 | task service ability error. | 4900 4901**Example** 4902 4903 ```ts 4904 import { BusinessError } from '@kit.BasicServicesKit'; 4905 4906 // Prepare the GroupConfig object. 4907 let config: request.agent.GroupConfig = { 4908 notification: {}, 4909 }; 4910 // Call the createGroup API to create a group. 4911 request.agent.createGroup(config).then((gid: string) => { 4912 console.info(`Succeeded in creating a download task group. `); 4913 }).catch((err: BusinessError) => { 4914 console.error(`Failed to create a download group, Code: ${err.code}, message: ${err.message}`); 4915 }); 4916 ``` 4917 4918## request.agent.attachGroup<sup>15+</sup> 4919 4920attachGroup(gid: string, tids: string[]): Promise\<void\> 4921 4922Attaches multiple download task IDs to a specified group ID. This API uses a promise to return the result. 4923 4924If any task ID does not meet the attachment conditions, all tasks in the list will not be added to the group. 4925 4926**System capability**: SystemCapability.Request.FileTransferAgent 4927 4928**Parameters** 4929 4930| Name | Type | Mandatory| Description | 4931|------|----------|----|---------------------| 4932| gid | string | Yes | Target group ID. | 4933| tids | string[] | Yes | List of task IDs to attach.| 4934 4935**Return value** 4936 4937| Type | Description | 4938|-----------------|------------| 4939| Promise<void> | Promise that returns no value.| 4940 4941**Error codes** 4942 4943For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4944 4945| ID | Error Message | 4946|----------|------------------------------------------------------------------------------------------------| 4947| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4948| 13400003 | task service ability error | 4949| 21900005 | task mode error | 4950| 21900007 | task state error | 4951| 21900008 | group deleted or not found | 4952 4953**Example** 4954 4955 ```ts 4956 import { BusinessError } from '@kit.BasicServicesKit'; 4957 4958 // Prepare the group ID and task ID list. 4959 let groupId: string = "123456789"; 4960 let taskIds: string[] = ["1111", "2222", "3333", "4444"]; 4961 // Call the attachGroup API to add a task ID list to the group. 4962 request.agent.attachGroup(groupId, taskIds).then(() => { 4963 console.info(`Succeeded in attaching tasks to the download task group.`); 4964 }).catch((err: BusinessError) => { 4965 console.error(`Failed to attach tasks to the download group, Code: ${err.code}, message: ${err.message}`); 4966 }); 4967 ``` 4968 4969## request.agent.deleteGroup<sup>15+</sup> 4970 4971deleteGroup(gid: string): Promise\<void\> 4972 4973Deletes a specified group. No task can be added to the group. This API uses a promise to return the result. 4974 4975When all tasks in a group are succeeded, failed, or removed and the group is deleted , the completion and failure notifications of this group are displayed. 4976 4977**System capability**: SystemCapability.Request.FileTransferAgent 4978 4979**Parameters** 4980 4981| Name | Type | Mandatory| Description | 4982|------|----------|----|---------| 4983| gid | string | Yes | Target group ID.| 4984 4985**Return value** 4986 4987| Type | Description | 4988|-----------------|------------| 4989| Promise<void> | Promise that returns no value.| 4990 4991**Error codes** 4992 4993For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4994 4995| ID | Error Message | 4996|----------|------------------------------------------------------------------------------------------------| 4997| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4998| 13400003 | task service ability error | 4999| 21900008 | group deleted or not found | 5000 5001**Example** 5002 5003 ```ts 5004 import { BusinessError } from '@kit.BasicServicesKit'; 5005 5006 // Prepare the group ID. 5007 let groupId: string = "123456789"; 5008 5009 // Call the deleteGroup API to delete a group. 5010 request.agent.deleteGroup(groupId).then(() => { 5011 console.info(`Succeeded in deleting the download task group.`); 5012 }).catch((err: BusinessError) => { 5013 console.error(`Failed to delete the download group, Code: ${err.code}, message: ${err.message}`); 5014 }); 5015 ``` 5016