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. Options are as follows:<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; since API version 15, the value contains a maximum of 8192 characters. [Intercepting HTTP](../../basic-services/request/app-file-upload-download.md#adding-network-configuration) is supported.| 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 the information about 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; since API version 15, the value contains a maximum of 8192 characters. [Intercepting HTTP](../../basic-services/request/app-file-upload-download.md#adding-network-configuration) is supported.| 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 values are as follows:<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.<br>- **true**: The download status is displayed.<br>- **false** (default): The download status is not displayed.| 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**System capability**: SystemCapability.Request.FileTransferAgent 2400 2401| Name| Type| Mandatory| Description| 2402| -------- | -------- | -------- | -------- | 2403| path | string | Yes| File path.<br>Relative path, which is in the cache directory of the caller,<br>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**,<br>for example, **internal://cache/path/to/file.txt**.<br>Application sandbox directory. Only the **base** directory and its subdirectories are supported, <br>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,<br>for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>- User public file,<br>for example, **file://media/Photo/path/to/file.img**. Only frontend tasks are supported.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2404| mimeType<sup>(deprecated)</sup> | string | No| MIME type of the file, which is obtained from the file name. The default value is the file name extension.<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br> This API is deprecated since API version 18. You are advised to use **contentType** instead.| 2405| contentType<sup>18+</sup> | string | No| Content type of the file. The default value is the file name extension. This option is filled in the **Content-Type** field specified in the HTTP form.| 2406| filename | string | No| File name. The default value is obtained from the file path.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2407| extras | object | No| Additional information. This parameter is not included in HTTP requests.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2408 2409 2410## FormItem<sup>10+</sup> 2411Describes the form item of a task. 2412 2413**Atomic service API**: This API can be used in atomic services since API version 11. 2414 2415**System capability**: SystemCapability.Request.FileTransferAgent 2416 2417| Name| Type| Mandatory| Description| 2418| -------- | -------- | -------- | -------- | 2419| name | string | Yes| Form parameter name.| 2420| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes| Form parameter value.| 2421 2422 2423## Config<sup>10+</sup> 2424Provides the configuration information of an upload or download task. 2425 2426**System capability**: SystemCapability.Request.FileTransferAgent 2427 2428| Name| Type| Mandatory| Description| 2429| -------- | -------- | -------- | -------- | 2430| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2431| url | string | Yes| Resource URL. From API version 6 to 14, the value contains a maximum of 2048 characters; since API version 15, the value contains a maximum of 8192 characters. [Intercepting HTTP](../../basic-services/request/app-file-upload-download.md#adding-network-configuration) is supported.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2432| title | string | No| Task title. The value contains a maximum of 256 characters. The default value is **upload** or **download** in lowercase. Set the value to that of **action**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2433| description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2434| mode | [Mode](#mode10) | No| Task mode. The default mode is background.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2435| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.<br>- **true**: Overwrite the existing file.<br>- **false**: Do not overwrite the existing file. In this case, the download fails.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2436| method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.<br>- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.<br>- If the task is a download, use **GET** or **POST**. The default value is **GET**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2437| headers | object | No| HTTP headers to be included in the task.<br>- If the task is an upload, the default **Content-Type** is **multipart/form-data**.<br>- If the task is a download, the default **Content-Type** is **application/json**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2438| data | string \| Array<[FormItem](#formitem10)> | No| Task data.<br>- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.<br>- If the task is an upload, the value is Array<[FormItem](#formitem10)>. 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.| 2439| saveas | string | No| Path for storing downloaded files. The options are as follows:<br>- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.<br>- Internal protocol path, which can be **internal://** or its subdirectory. **internal** indicates the cache directory of the caller (that is, the input **context**), and **internal://cache** corresponds to **context.cacheDir**, for example, **internal://cache/path/to/file.txt**.<br>- Application sandbox directory. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.<br>- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>The default value is the cache directory of the caller (that is, the input **context**). The default file name is the part truncated from the last slash (/) in the URL.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2440| network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2441| metered | boolean | No| Whether the task is allowed on a metered connection.<br>- **true**: The task is allowed on a metered connection.<br>- **false** (default): The task is not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2442| roaming | boolean | No| Whether the task is allowed on a roaming network.<br>- **true** (default): The task is allowed on a roaming network.<br>- **false**: The task is not allowed on a roaming network.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2443| retry | boolean | No| Whether automatic retry is enabled for the task. This parameter is only applicable to background tasks.<br>- **true** (default): The automatic retry is enabled.<br>- **false**: The automatic retry is disabled.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2444| redirect | boolean | No| Whether redirection is allowed.<br>- **true** (default): The redirection is allowed.<br>- **false**: The redirection is not allowed.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2445| proxy<sup>12+</sup> | string | No| Proxy address. The value contains a maximum of 512 characters.<br>It is in the format of http://\<domain or address\>:\<port\>. By default, this parameter is left blank.| 2446| index | number | No| Path index of the task. It is usually used for resumable downloads. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2447| begins | number | No| File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the beginning of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2448| ends | number | No| File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the end of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2449| gauge | boolean | No| Whether to send progress notifications. This parameter applies only to background tasks. The default value is **false**.<br>- **false**: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.<br>- **true**: Progress notifications are sent to indicate the result of each file.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2450| precise | boolean | No| - If this parameter is set to **true**, the task fails when the file size cannot be obtained.<br>- If this parameter is set to **false**, the task continues when the file size is set to **-1**.<br>The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2451| token | string | No| Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2452| priority<sup>11+</sup> | number | No| Priority of the task. For tasks in the same mode, a smaller value indicates a higher priority.<br>Default value: **0**| 2453| extras | object | No| Additional information of the task. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2454| multipart<sup>15+</sup> | boolean | No| Whether to use a single request to upload multiple files. If yes, **multipart/form-data** must be used.<br>- **false** (default): A single request is used to upload one file.<br>- **true**: A single request is used to upload multiple files.<br> | 2455| notification<sup>15+</sup> | [Notification](#notification15) | No| Custom settings for the notification bar.| 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.<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.| 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**<br>When [request.agent.search<sup>10+</sup>](#requestagentsearch10-1) is used for query, this value must be within the range of [after,before] for the task ID to be obtained. For details about **before** and **after**, see [Filter](#filter10). | 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.<br>- **true**: The automatic retry is enabled.<br>- **false**: The automatic retry is disabled. | 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 2559## HttpResponse<sup>12+</sup> 2560Describes the data structure of the task response header. 2561 2562**Atomic service API**: This API can be used in atomic services since API version 12. 2563 2564**System capability**: SystemCapability.Request.FileTransferAgent 2565 2566| Name| Type| Mandatory| Description| 2567| -------- | -------- | -------- | -------- | 2568| version | string | Yes| HTTP version.| 2569| statusCode | number | Yes| HTTP response status code.| 2570| reason | string | Yes| HTTP response cause.| 2571| headers | Map<string, Array<string>> | Yes| HTTP response header.| 2572 2573## Notification<sup>15+</sup> 2574 2575Describes the custom information of the notification bar. 2576 2577**System capability**: SystemCapability.Request.FileTransferAgent 2578 2579| Name | Type | Mandatory| Description | 2580|---------|--------|----|-----------------------------------------| 2581| title | string | No | Custom title, with a maximum of 1024 bytes. The default title is used if this parameter is not set. | 2582| text | string | No | Custom body text, with a maximum of 3072 bytes. The default text is used if this parameter is not set. | 2583 2584## GroupConfig<sup>15+</sup> 2585 2586Describes group configuration options for download tasks. 2587 2588**System capability**: SystemCapability.Request.FileTransferAgent 2589 2590| Name | Type | Mandatory| Description | 2591|--------------|-----------------------------------------------|----|--------------------------------------------------------------| 2592| gauge | boolean | No | Whether to send progress notifications. This parameter applies only to background tasks.<br>- **true**: The progress, success, and failure notifications are sent.<br>- **false**: Only success and failure notifications are sent.<br>The default value is **false**.| 2593| notification<sup>15+</sup> | [Notification](#notification15) | Yes | Custom settings for the notification bar. | 2594 2595## Task<sup>10+</sup> 2596Implements 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). 2597 2598### Attributes 2599Task attributes include the task ID and task configuration. 2600 2601**Atomic service API**: This API can be used in atomic services since API version 11. 2602 2603**System capability**: SystemCapability.Request.FileTransferAgent 2604 2605| Name| Type| Mandatory| Description| 2606| -------- | -------- | -------- | -------- | 2607| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.| 2608| config | [Config](#config10) | Yes| Task configuration.| 2609 2610> **NOTE** 2611> 2612> The **Task** object and its mounting callback function are released and automatically reclaimed by the system after the **remove** method is called. 2613 2614### on('progress')<sup>10+</sup> 2615 2616on(event: 'progress', callback: (progress: [Progress](#progress10)) => void): void 2617 2618Subscribes to task progress changes. This API uses an asynchronous callback to return the result. 2619 2620**Atomic service API**: This API can be used in atomic services since API version 11. 2621 2622**System capability**: SystemCapability.Request.FileTransferAgent 2623 2624**Parameters** 2625 2626| Name| Type| Mandatory| Description| 2627| -------- | -------- | -------- | -------- | 2628| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 2629| callback | function | Yes| Callback used to return the data structure of the task progress.| 2630 2631**Error codes** 2632 2633For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2634 2635| ID| Error Message| 2636| -------- | -------- | 2637| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 2638 2639**Example** 2640 2641 ```ts 2642 import { BusinessError } from '@kit.BasicServicesKit'; 2643 2644 let attachments: Array<request.agent.FormItem> = [{ 2645 name: "taskOnTest", 2646 value: { 2647 filename: "taskOnTest.avi", 2648 mimeType: "application/octet-stream", 2649 path: "./taskOnTest.avi", 2650 } 2651 }]; 2652 let config: request.agent.Config = { 2653 action: request.agent.Action.UPLOAD, 2654 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2655 title: 'taskOnTest', 2656 description: 'Sample code for event listening', 2657 mode: request.agent.Mode.FOREGROUND, 2658 overwrite: false, 2659 method: "PUT", 2660 data: attachments, 2661 saveas: "./", 2662 network: request.agent.Network.CELLULAR, 2663 metered: false, 2664 roaming: true, 2665 retry: true, 2666 redirect: true, 2667 index: 0, 2668 begins: 0, 2669 ends: -1, 2670 gauge: false, 2671 precise: false, 2672 token: "it is a secret" 2673 }; 2674 let createOnCallback = (progress: request.agent.Progress) => { 2675 console.info('upload task progress.'); 2676 }; 2677 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2678 task.on('progress', createOnCallback); 2679 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2680 task.start(); 2681 }).catch((err: BusinessError) => { 2682 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2683 }); 2684 ``` 2685 2686> **NOTE** 2687> 2688> 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). 2689 2690### on('completed')<sup>10+</sup> 2691 2692on(event: 'completed', callback: (progress: [Progress](#progress10)) => void): void 2693 2694Subscribes to task completion events. This API uses an asynchronous callback to return the result. 2695 2696**Atomic service API**: This API can be used in atomic services since API version 11. 2697 2698**System capability**: SystemCapability.Request.FileTransferAgent 2699 2700**Parameters** 2701 2702| Name| Type| Mandatory| Description| 2703| -------- | -------- | -------- | -------- | 2704| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 2705| callback | function | Yes| Callback used to return the data structure of the task progress.| 2706 2707**Error codes** 2708 2709For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2710 2711| ID| Error Message| 2712| -------- | -------- | 2713| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 2714 2715**Example** 2716 2717 ```ts 2718 import { BusinessError } from '@kit.BasicServicesKit'; 2719 2720 let attachments: Array<request.agent.FormItem> = [{ 2721 name: "taskOnTest", 2722 value: { 2723 filename: "taskOnTest.avi", 2724 mimeType: "application/octet-stream", 2725 path: "./taskOnTest.avi", 2726 } 2727 }]; 2728 let config: request.agent.Config = { 2729 action: request.agent.Action.UPLOAD, 2730 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2731 title: 'taskOnTest', 2732 description: 'Sample code for event listening', 2733 mode: request.agent.Mode.FOREGROUND, 2734 overwrite: false, 2735 method: "PUT", 2736 data: attachments, 2737 saveas: "./", 2738 network: request.agent.Network.CELLULAR, 2739 metered: false, 2740 roaming: true, 2741 retry: true, 2742 redirect: true, 2743 index: 0, 2744 begins: 0, 2745 ends: -1, 2746 gauge: false, 2747 precise: false, 2748 token: "it is a secret" 2749 }; 2750 let createOnCallback = (progress: request.agent.Progress) => { 2751 console.info('upload task completed.'); 2752 }; 2753 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2754 task.on('completed', createOnCallback); 2755 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2756 task.start(); 2757 }).catch((err: BusinessError) => { 2758 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2759 }); 2760 ``` 2761 2762> **NOTE** 2763> 2764> 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). 2765 2766### on('failed')<sup>10+</sup> 2767 2768on(event: 'failed', callback: (progress: [Progress](#progress10)) => void): void 2769 2770Subscribes 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. 2771 2772**Atomic service API**: This API can be used in atomic services since API version 11. 2773 2774**System capability**: SystemCapability.Request.FileTransferAgent 2775 2776**Parameters** 2777 2778| Name| Type| Mandatory| Description| 2779| -------- | -------- | -------- | -------- | 2780| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 2781| callback | function | Yes| Callback used to return the data structure of the task progress.| 2782 2783**Error codes** 2784 2785For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2786 2787| ID| Error Message| 2788| -------- | -------- | 2789| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 2790 2791**Example** 2792 2793 ```ts 2794 import { BusinessError } from '@kit.BasicServicesKit'; 2795 2796 let attachments: Array<request.agent.FormItem> = [{ 2797 name: "taskOnTest", 2798 value: { 2799 filename: "taskOnTest.avi", 2800 mimeType: "application/octet-stream", 2801 path: "./taskOnTest.avi", 2802 } 2803 }]; 2804 let config: request.agent.Config = { 2805 action: request.agent.Action.UPLOAD, 2806 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2807 title: 'taskOnTest', 2808 description: 'Sample code for event listening', 2809 mode: request.agent.Mode.FOREGROUND, 2810 overwrite: false, 2811 method: "PUT", 2812 data: attachments, 2813 saveas: "./", 2814 network: request.agent.Network.CELLULAR, 2815 metered: false, 2816 roaming: true, 2817 retry: true, 2818 redirect: true, 2819 index: 0, 2820 begins: 0, 2821 ends: -1, 2822 gauge: false, 2823 precise: false, 2824 token: "it is a secret" 2825 }; 2826 let createOnCallback = (progress: request.agent.Progress) => { 2827 console.info('upload task failed.'); 2828 }; 2829 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2830 task.on('failed', createOnCallback); 2831 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2832 task.start(); 2833 }).catch((err: BusinessError) => { 2834 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2835 }); 2836 ``` 2837 2838> **NOTE** 2839> 2840> 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). 2841 2842### on('pause')<sup>11+</sup> 2843 2844on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void 2845 2846Subscribes to task pause events. This API uses an asynchronous callback to return the result. 2847 2848**System capability**: SystemCapability.Request.FileTransferAgent 2849 2850**Parameters** 2851 2852| Name| Type| Mandatory| Description| 2853| -------- | -------- | -------- | -------- | 2854| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 2855| callback | function | Yes| Callback used to return the data structure of the task progress.| 2856 2857**Error codes** 2858 2859For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2860 2861| ID| Error Message| 2862| -------- | -------- | 2863| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 2864 2865**Example** 2866 2867 ```ts 2868 import { BusinessError } from '@kit.BasicServicesKit'; 2869 2870 let attachments: Array<request.agent.FormItem> = [{ 2871 name: "taskOnTest", 2872 value: { 2873 filename: "taskOnTest.avi", 2874 mimeType: "application/octet-stream", 2875 path: "./taskOnTest.avi", 2876 } 2877 }]; 2878 let config: request.agent.Config = { 2879 action: request.agent.Action.UPLOAD, 2880 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2881 title: 'taskOnTest', 2882 description: 'Sample code for event listening', 2883 mode: request.agent.Mode.FOREGROUND, 2884 overwrite: false, 2885 method: "PUT", 2886 data: attachments, 2887 saveas: "./", 2888 network: request.agent.Network.CELLULAR, 2889 metered: false, 2890 roaming: true, 2891 retry: true, 2892 redirect: true, 2893 index: 0, 2894 begins: 0, 2895 ends: -1, 2896 gauge: false, 2897 precise: false, 2898 token: "it is a secret" 2899 }; 2900 let createOnCallback = (progress: request.agent.Progress) => { 2901 console.info('upload task pause.'); 2902 }; 2903 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2904 task.on('pause', createOnCallback); 2905 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2906 task.start(); 2907 }).catch((err: BusinessError) => { 2908 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2909 }); 2910 ``` 2911 2912> **NOTE** 2913> 2914> 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). 2915 2916### on('resume')<sup>11+</sup> 2917 2918on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void 2919 2920Subscribes to task resume events. This API uses an asynchronous callback to return the result. 2921 2922**System capability**: SystemCapability.Request.FileTransferAgent 2923 2924**Parameters** 2925 2926| Name| Type| Mandatory| Description| 2927| -------- | -------- | -------- | -------- | 2928| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 2929| callback | function | Yes| Callback used to return the data structure of the task progress.| 2930 2931**Error codes** 2932 2933For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2934 2935| ID| Error Message| 2936| -------- | -------- | 2937| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 2938 2939**Example** 2940 2941 ```ts 2942 import { BusinessError } from '@kit.BasicServicesKit'; 2943 2944 let attachments: Array<request.agent.FormItem> = [{ 2945 name: "taskOnTest", 2946 value: { 2947 filename: "taskOnTest.avi", 2948 mimeType: "application/octet-stream", 2949 path: "./taskOnTest.avi", 2950 } 2951 }]; 2952 let config: request.agent.Config = { 2953 action: request.agent.Action.UPLOAD, 2954 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2955 title: 'taskOnTest', 2956 description: 'Sample code for event listening', 2957 mode: request.agent.Mode.FOREGROUND, 2958 overwrite: false, 2959 method: "PUT", 2960 data: attachments, 2961 saveas: "./", 2962 network: request.agent.Network.CELLULAR, 2963 metered: false, 2964 roaming: true, 2965 retry: true, 2966 redirect: true, 2967 index: 0, 2968 begins: 0, 2969 ends: -1, 2970 gauge: false, 2971 precise: false, 2972 token: "it is a secret" 2973 }; 2974 let createOnCallback = (progress: request.agent.Progress) => { 2975 console.info('upload task resume.'); 2976 }; 2977 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2978 task.on('resume', createOnCallback); 2979 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2980 task.start(); 2981 }).catch((err: BusinessError) => { 2982 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2983 }); 2984 ``` 2985 2986> **NOTE** 2987> 2988> 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). 2989 2990### on('remove')<sup>11+</sup> 2991 2992on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void 2993 2994Subscribes to task removal events. This API uses an asynchronous callback to return the result. 2995 2996**System capability**: SystemCapability.Request.FileTransferAgent 2997 2998**Parameters** 2999 3000| Name| Type| Mandatory| Description| 3001| -------- | -------- | -------- | -------- | 3002| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 3003| callback | function | Yes| Callback used to return the data structure of the task progress.| 3004 3005**Error codes** 3006 3007For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3008 3009| ID| Error Message| 3010| -------- | -------- | 3011| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3012 3013**Example** 3014 3015 ```ts 3016 import { BusinessError } from '@kit.BasicServicesKit'; 3017 3018 let attachments: Array<request.agent.FormItem> = [{ 3019 name: "taskOnTest", 3020 value: { 3021 filename: "taskOnTest.avi", 3022 mimeType: "application/octet-stream", 3023 path: "./taskOnTest.avi", 3024 } 3025 }]; 3026 let config: request.agent.Config = { 3027 action: request.agent.Action.UPLOAD, 3028 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3029 title: 'taskOnTest', 3030 description: 'Sample code for event listening', 3031 mode: request.agent.Mode.FOREGROUND, 3032 overwrite: false, 3033 method: "PUT", 3034 data: attachments, 3035 saveas: "./", 3036 network: request.agent.Network.CELLULAR, 3037 metered: false, 3038 roaming: true, 3039 retry: true, 3040 redirect: true, 3041 index: 0, 3042 begins: 0, 3043 ends: -1, 3044 gauge: false, 3045 precise: false, 3046 token: "it is a secret" 3047 }; 3048 let createOnCallback = (progress: request.agent.Progress) => { 3049 console.info('upload task remove.'); 3050 }; 3051 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3052 task.on('remove', createOnCallback); 3053 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3054 task.start(); 3055 }).catch((err: BusinessError) => { 3056 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3057 }); 3058 ``` 3059 3060> **NOTE** 3061> 3062> 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). 3063 3064### on('response')<sup>12+</sup> 3065 3066on(event: 'response', callback: Callback<HttpResponse>): void 3067 3068Subscribes to task response headers. This API uses an asynchronous callback to return the result. 3069 3070**Atomic service API**: This API can be used in atomic services since API version 12. 3071 3072**System capability**: SystemCapability.Request.FileTransferAgent 3073 3074**Parameters** 3075 3076| Name| Type| Mandatory| Description| 3077| -------- | -------- | -------- | -------- | 3078| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3079| callback | function | Yes| Callback used to return the data structure of the task response header.| 3080 3081**Error codes** 3082 3083For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3084 3085| ID| Error Message| 3086| -------- | -------- | 3087| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3088 3089**Example** 3090 3091 ```ts 3092 import { BusinessError } from '@kit.BasicServicesKit'; 3093 3094 let attachments: Array<request.agent.FormItem> = [{ 3095 name: "taskOnTest", 3096 value: { 3097 filename: "taskOnTest.avi", 3098 mimeType: "application/octet-stream", 3099 path: "./taskOnTest.avi", 3100 } 3101 }]; 3102 let config: request.agent.Config = { 3103 action: request.agent.Action.UPLOAD, 3104 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3105 title: 'taskOnTest', 3106 description: 'Sample code for event listening', 3107 mode: request.agent.Mode.FOREGROUND, 3108 overwrite: false, 3109 method: "PUT", 3110 data: attachments, 3111 saveas: "./", 3112 network: request.agent.Network.CELLULAR, 3113 metered: false, 3114 roaming: true, 3115 retry: true, 3116 redirect: true, 3117 index: 0, 3118 begins: 0, 3119 ends: -1, 3120 gauge: false, 3121 precise: false, 3122 token: "it is a secret" 3123 }; 3124 let createOnCallback = (response: request.agent.HttpResponse) => { 3125 console.info('upload task response.'); 3126 }; 3127 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3128 task.on('response', createOnCallback); 3129 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3130 task.start(); 3131 }).catch((err: BusinessError) => { 3132 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3133 }); 3134 ``` 3135 3136> **NOTE** 3137> 3138> 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). 3139 3140### off('progress')<sup>10+</sup> 3141 3142off(event: 'progress', callback?: (progress: [Progress](#progress10)) => void): void 3143 3144Unsubscribes from task progress events. 3145 3146**Atomic service API**: This API can be used in atomic services since API version 11. 3147 3148**System capability**: SystemCapability.Request.FileTransferAgent 3149 3150**Parameters** 3151 3152| Name| Type| Mandatory| Description| 3153| -------- | -------- | -------- | -------- | 3154| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 3155| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3156 3157**Error codes** 3158 3159For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3160 3161| ID| Error Message| 3162| -------- | -------- | 3163| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3164 3165**Example** 3166 3167 ```ts 3168 import { BusinessError } from '@kit.BasicServicesKit'; 3169 3170 let attachments: Array<request.agent.FormItem> = [{ 3171 name: "taskOffTest", 3172 value: { 3173 filename: "taskOffTest.avi", 3174 mimeType: "application/octet-stream", 3175 path: "./taskOffTest.avi", 3176 } 3177 }]; 3178 let config: request.agent.Config = { 3179 action: request.agent.Action.UPLOAD, 3180 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3181 title: 'taskOffTest', 3182 description: 'Sample code for event listening', 3183 mode: request.agent.Mode.FOREGROUND, 3184 overwrite: false, 3185 method: "PUT", 3186 data: attachments, 3187 saveas: "./", 3188 network: request.agent.Network.CELLULAR, 3189 metered: false, 3190 roaming: true, 3191 retry: true, 3192 redirect: true, 3193 index: 0, 3194 begins: 0, 3195 ends: -1, 3196 gauge: false, 3197 precise: false, 3198 token: "it is a secret" 3199 }; 3200 let createOffCallback1 = (progress: request.agent.Progress) => { 3201 console.info('upload task progress.'); 3202 }; 3203 let createOffCallback2 = (progress: request.agent.Progress) => { 3204 console.info('upload task progress.'); 3205 }; 3206 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3207 task.on('progress', createOffCallback1); 3208 task.on('progress', createOffCallback2); 3209 // Unsubscribe from createOffCallback1. 3210 task.off('progress', createOffCallback1); 3211 // Unsubscribe from all callbacks of task progress changes. 3212 task.off('progress'); 3213 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3214 task.start(); 3215 }).catch((err: BusinessError) => { 3216 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3217 }); 3218 ``` 3219 3220> **NOTE** 3221> 3222> 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). 3223 3224### off('completed')<sup>10+</sup> 3225 3226off(event: 'completed', callback?: (progress: [Progress](#progress10)) => void): void 3227 3228Unsubscribes from task completion events. 3229 3230**Atomic service API**: This API can be used in atomic services since API version 11. 3231 3232**System capability**: SystemCapability.Request.FileTransferAgent 3233 3234**Parameters** 3235 3236| Name| Type| Mandatory| Description| 3237| -------- | -------- | -------- | -------- | 3238| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 3239| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3240 3241**Error codes** 3242 3243For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3244 3245| ID| Error Message| 3246| -------- | -------- | 3247| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3248 3249**Example** 3250 3251 ```ts 3252 import { BusinessError } from '@kit.BasicServicesKit'; 3253 3254 let attachments: Array<request.agent.FormItem> = [{ 3255 name: "taskOffTest", 3256 value: { 3257 filename: "taskOffTest.avi", 3258 mimeType: "application/octet-stream", 3259 path: "./taskOffTest.avi", 3260 } 3261 }]; 3262 let config: request.agent.Config = { 3263 action: request.agent.Action.UPLOAD, 3264 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3265 title: 'taskOffTest', 3266 description: 'Sample code for event listening', 3267 mode: request.agent.Mode.FOREGROUND, 3268 overwrite: false, 3269 method: "PUT", 3270 data: attachments, 3271 saveas: "./", 3272 network: request.agent.Network.CELLULAR, 3273 metered: false, 3274 roaming: true, 3275 retry: true, 3276 redirect: true, 3277 index: 0, 3278 begins: 0, 3279 ends: -1, 3280 gauge: false, 3281 precise: false, 3282 token: "it is a secret" 3283 }; 3284 let createOffCallback1 = (progress: request.agent.Progress) => { 3285 console.info('upload task completed.'); 3286 }; 3287 let createOffCallback2 = (progress: request.agent.Progress) => { 3288 console.info('upload task completed.'); 3289 }; 3290 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3291 task.on('completed', createOffCallback1); 3292 task.on('completed', createOffCallback2); 3293 // Unsubscribe from createOffCallback1. 3294 task.off('completed', createOffCallback1); 3295 // Unsubscribe from all callbacks of the task completion events. 3296 task.off('completed'); 3297 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3298 task.start(); 3299 }).catch((err: BusinessError) => { 3300 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3301 }); 3302 ``` 3303 3304> **NOTE** 3305> 3306> 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). 3307 3308### off('failed')<sup>10+</sup> 3309 3310off(event: 'failed', callback?: (progress: [Progress](#progress10)) => void): void 3311 3312Unsubscribes from task failure events. 3313 3314**Atomic service API**: This API can be used in atomic services since API version 11. 3315 3316**System capability**: SystemCapability.Request.FileTransferAgent 3317 3318**Parameters** 3319 3320| Name| Type| Mandatory| Description| 3321| -------- | -------- | -------- | -------- | 3322| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 3323| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3324 3325**Error codes** 3326 3327For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3328 3329| ID| Error Message| 3330| -------- | -------- | 3331| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3332 3333**Example** 3334 3335 ```ts 3336 import { BusinessError } from '@kit.BasicServicesKit'; 3337 3338 let attachments: Array<request.agent.FormItem> = [{ 3339 name: "taskOffTest", 3340 value: { 3341 filename: "taskOffTest.avi", 3342 mimeType: "application/octet-stream", 3343 path: "./taskOffTest.avi", 3344 } 3345 }]; 3346 let config: request.agent.Config = { 3347 action: request.agent.Action.UPLOAD, 3348 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3349 title: 'taskOffTest', 3350 description: 'Sample code for event listening', 3351 mode: request.agent.Mode.FOREGROUND, 3352 overwrite: false, 3353 method: "PUT", 3354 data: attachments, 3355 saveas: "./", 3356 network: request.agent.Network.CELLULAR, 3357 metered: false, 3358 roaming: true, 3359 retry: true, 3360 redirect: true, 3361 index: 0, 3362 begins: 0, 3363 ends: -1, 3364 gauge: false, 3365 precise: false, 3366 token: "it is a secret" 3367 }; 3368 let createOffCallback1 = (progress: request.agent.Progress) => { 3369 console.info('upload task failed.'); 3370 }; 3371 let createOffCallback2 = (progress: request.agent.Progress) => { 3372 console.info('upload task failed.'); 3373 }; 3374 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3375 task.on('failed', createOffCallback1); 3376 task.on('failed', createOffCallback2); 3377 // Unsubscribe from createOffCallback1. 3378 task.off('failed', createOffCallback1); 3379 // Unsubscribe from all callbacks of the task failure events. 3380 task.off('failed'); 3381 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3382 task.start(); 3383 }).catch((err: BusinessError) => { 3384 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3385 }); 3386 ``` 3387 3388> **NOTE** 3389> 3390> 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). 3391 3392### off('pause')<sup>11+</sup> 3393 3394off(event: 'pause', callback?: (progress: [Progress](#progress10)) => void): void 3395 3396Unsubscribes from the foreground task pause event. 3397 3398**System capability**: SystemCapability.Request.FileTransferAgent 3399 3400**Parameters** 3401 3402| Name| Type| Mandatory| Description| 3403| -------- | -------- | -------- | -------- | 3404| event | string | Yes| Type of the event to subscribe to.<br>- **'pause'**: task pause event.| 3405| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3406 3407**Error codes** 3408 3409For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3410 3411| ID| Error Message| 3412| -------- | -------- | 3413| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3414 3415**Example** 3416 3417 ```ts 3418 import { BusinessError } from '@kit.BasicServicesKit'; 3419 3420 let attachments: Array<request.agent.FormItem> = [{ 3421 name: "taskOffTest", 3422 value: { 3423 filename: "taskOffTest.avi", 3424 mimeType: "application/octet-stream", 3425 path: "./taskOffTest.avi", 3426 } 3427 }]; 3428 let config: request.agent.Config = { 3429 action: request.agent.Action.UPLOAD, 3430 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3431 title: 'taskOffTest', 3432 description: 'Sample code for event listening', 3433 mode: request.agent.Mode.FOREGROUND, 3434 overwrite: false, 3435 method: "PUT", 3436 data: attachments, 3437 saveas: "./", 3438 network: request.agent.Network.CELLULAR, 3439 metered: false, 3440 roaming: true, 3441 retry: true, 3442 redirect: true, 3443 index: 0, 3444 begins: 0, 3445 ends: -1, 3446 gauge: false, 3447 precise: false, 3448 token: "it is a secret" 3449 }; 3450 let createOffCallback1 = (progress: request.agent.Progress) => { 3451 console.info('upload task pause.'); 3452 }; 3453 let createOffCallback2 = (progress: request.agent.Progress) => { 3454 console.info('upload task pause.'); 3455 }; 3456 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3457 task.on('pause', createOffCallback1); 3458 task.on('pause', createOffCallback2); 3459 // Unsubscribe from createOffCallback1. 3460 task.off('pause', createOffCallback1); 3461 // Unsubscribe from all callbacks of the foreground task pause event. 3462 task.off('pause'); 3463 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3464 task.start(); 3465 }).catch((err: BusinessError) => { 3466 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3467 }); 3468 ``` 3469 3470> **NOTE** 3471> 3472> 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). 3473 3474### off('resume')<sup>11+</sup> 3475 3476off(event: 'resume', callback?: (progress: [Progress](#progress10)) => void): void 3477 3478Unsubscribes from the foreground task resume event. 3479 3480**System capability**: SystemCapability.Request.FileTransferAgent 3481 3482**Parameters** 3483 3484| Name| Type| Mandatory| Description| 3485| -------- | -------- | -------- | -------- | 3486| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 3487| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3488 3489**Error codes** 3490 3491For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3492 3493| ID| Error Message| 3494| -------- | -------- | 3495| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3496 3497**Example** 3498 3499 ```ts 3500 import { BusinessError } from '@kit.BasicServicesKit'; 3501 3502 let attachments: Array<request.agent.FormItem> = [{ 3503 name: "taskOffTest", 3504 value: { 3505 filename: "taskOffTest.avi", 3506 mimeType: "application/octet-stream", 3507 path: "./taskOffTest.avi", 3508 } 3509 }]; 3510 let config: request.agent.Config = { 3511 action: request.agent.Action.UPLOAD, 3512 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3513 title: 'taskOffTest', 3514 description: 'Sample code for event listening', 3515 mode: request.agent.Mode.FOREGROUND, 3516 overwrite: false, 3517 method: "PUT", 3518 data: attachments, 3519 saveas: "./", 3520 network: request.agent.Network.CELLULAR, 3521 metered: false, 3522 roaming: true, 3523 retry: true, 3524 redirect: true, 3525 index: 0, 3526 begins: 0, 3527 ends: -1, 3528 gauge: false, 3529 precise: false, 3530 token: "it is a secret" 3531 }; 3532 let createOffCallback1 = (progress: request.agent.Progress) => { 3533 console.info('upload task resume.'); 3534 }; 3535 let createOffCallback2 = (progress: request.agent.Progress) => { 3536 console.info('upload task resume.'); 3537 }; 3538 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3539 task.on('resume', createOffCallback1); 3540 task.on('resume', createOffCallback2); 3541 // Unsubscribe from createOffCallback1. 3542 task.off('resume', createOffCallback1); 3543 // Unsubscribe from all callbacks of the foreground task resume event. 3544 task.off('resume'); 3545 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3546 task.start(); 3547 }).catch((err: BusinessError) => { 3548 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3549 }); 3550 ``` 3551 3552> **NOTE** 3553> 3554> 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). 3555 3556### off('remove')<sup>11+</sup> 3557 3558off(event: 'remove', callback?: (progress: [Progress](#progress10)) => void): void 3559 3560Unsubscribes from the task removal event. 3561 3562**System capability**: SystemCapability.Request.FileTransferAgent 3563 3564**Parameters** 3565 3566| Name| Type| Mandatory| Description| 3567| -------- | -------- | -------- | -------- | 3568| event | string | Yes| Type of the event to subscribe to.<br>- **'remove'**: task removal event.| 3569| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3570 3571**Error codes** 3572 3573For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3574 3575| ID| Error Message| 3576| -------- | -------- | 3577| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3578 3579**Example** 3580 3581 ```ts 3582 import { BusinessError } from '@kit.BasicServicesKit'; 3583 3584 let attachments: Array<request.agent.FormItem> = [{ 3585 name: "taskOffTest", 3586 value: { 3587 filename: "taskOffTest.avi", 3588 mimeType: "application/octet-stream", 3589 path: "./taskOffTest.avi", 3590 } 3591 }]; 3592 let config: request.agent.Config = { 3593 action: request.agent.Action.UPLOAD, 3594 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3595 title: 'taskOffTest', 3596 description: 'Sample code for event listening', 3597 mode: request.agent.Mode.FOREGROUND, 3598 overwrite: false, 3599 method: "PUT", 3600 data: attachments, 3601 saveas: "./", 3602 network: request.agent.Network.CELLULAR, 3603 metered: false, 3604 roaming: true, 3605 retry: true, 3606 redirect: true, 3607 index: 0, 3608 begins: 0, 3609 ends: -1, 3610 gauge: false, 3611 precise: false, 3612 token: "it is a secret" 3613 }; 3614 let createOffCallback1 = (progress: request.agent.Progress) => { 3615 console.info('upload task remove.'); 3616 }; 3617 let createOffCallback2 = (progress: request.agent.Progress) => { 3618 console.info('upload task remove.'); 3619 }; 3620 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3621 task.on('remove', createOffCallback1); 3622 task.on('remove', createOffCallback2); 3623 // Unsubscribe from createOffCallback1. 3624 task.off('remove', createOffCallback1); 3625 // Unsubscribe from all callbacks of the task removal event. 3626 task.off('remove'); 3627 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3628 task.start(); 3629 }).catch((err: BusinessError) => { 3630 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3631 }); 3632 ``` 3633 3634> **NOTE** 3635> 3636> 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). 3637 3638### off('response')<sup>12+</sup> 3639 3640off(event: 'response', callback?: Callback<HttpResponse>): void 3641 3642Unsubscribes from task response headers. 3643 3644**Atomic service API**: This API can be used in atomic services since API version 12. 3645 3646**System capability**: SystemCapability.Request.FileTransferAgent 3647 3648**Parameters** 3649 3650| Name| Type| Mandatory| Description| 3651| -------- | -------- | -------- | -------- | 3652| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3653| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3654 3655**Error codes** 3656 3657For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3658 3659| ID| Error Message| 3660| -------- | -------- | 3661| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 3662 3663**Example** 3664 3665 ```ts 3666 import { BusinessError } from '@kit.BasicServicesKit'; 3667 3668 let attachments: Array<request.agent.FormItem> = [{ 3669 name: "taskOffTest", 3670 value: { 3671 filename: "taskOffTest.avi", 3672 mimeType: "application/octet-stream", 3673 path: "./taskOffTest.avi", 3674 } 3675 }]; 3676 let config: request.agent.Config = { 3677 action: request.agent.Action.UPLOAD, 3678 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3679 title: 'taskOffTest', 3680 description: 'Sample code for event listening', 3681 mode: request.agent.Mode.FOREGROUND, 3682 overwrite: false, 3683 method: "PUT", 3684 data: attachments, 3685 saveas: "./", 3686 network: request.agent.Network.CELLULAR, 3687 metered: false, 3688 roaming: true, 3689 retry: true, 3690 redirect: true, 3691 index: 0, 3692 begins: 0, 3693 ends: -1, 3694 gauge: false, 3695 precise: false, 3696 token: "it is a secret" 3697 }; 3698 let createOffCallback1 = (progress: request.agent.HttpResponse) => { 3699 console.info('upload task response.'); 3700 }; 3701 let createOffCallback2 = (progress: request.agent.HttpResponse) => { 3702 console.info('upload task response.'); 3703 }; 3704 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3705 task.on('response', createOffCallback1); 3706 task.on('response', createOffCallback2); 3707 // Unsubscribe from createOffCallback1. 3708 task.off('response', createOffCallback1); 3709 // Unsubscribe from all callbacks of the task removal event. 3710 task.off('response'); 3711 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3712 task.start(); 3713 }).catch((err: BusinessError) => { 3714 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3715 }); 3716 ``` 3717 3718> **NOTE** 3719> 3720> 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). 3721 3722### start<sup>10+</sup> 3723 3724start(callback: AsyncCallback<void>): void 3725 3726Tasks in the following states can be started: 37271. Task created by **request.agent.create**. 37282. Download tasks that are created by **request.agent.create** but have failed or paused. 3729 3730**Required permissions**: ohos.permission.INTERNET 3731 3732**Atomic service API**: This API can be used in atomic services since API version 11. 3733 3734**System capability**: SystemCapability.Request.FileTransferAgent 3735 3736**Parameters** 3737 3738| Name| Type| Mandatory| Description| 3739| -------- | -------- | -------- | -------- | 3740| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3741 3742**Error codes** 3743 3744For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3745 3746| ID| Error Message| 3747| -------- | -------- | 3748| 201 | Permission denied. | 3749| 13400003 | task service ability error. | 3750| 21900007 | task state error. | 3751 3752**Example** 3753 3754 ```ts 3755 import { BusinessError } from '@kit.BasicServicesKit'; 3756 3757 let config: request.agent.Config = { 3758 action: request.agent.Action.DOWNLOAD, 3759 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3760 title: 'taskStartTest', 3761 description: 'Sample code for start the download task', 3762 mode: request.agent.Mode.BACKGROUND, 3763 overwrite: false, 3764 method: "GET", 3765 data: "", 3766 saveas: "./", 3767 network: request.agent.Network.CELLULAR, 3768 metered: false, 3769 roaming: true, 3770 retry: true, 3771 redirect: true, 3772 index: 0, 3773 begins: 0, 3774 ends: -1, 3775 gauge: false, 3776 precise: false, 3777 token: "it is a secret" 3778 }; 3779 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3780 task.start((err: BusinessError) => { 3781 if (err) { 3782 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3783 return; 3784 } 3785 console.info(`Succeeded in starting a download task.`); 3786 }); 3787 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3788 }).catch((err: BusinessError) => { 3789 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3790 }); 3791 ``` 3792 3793> **NOTE** 3794> 3795> 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). 3796 3797### start<sup>10+</sup> 3798 3799start(): Promise<void> 3800 3801Tasks in the following states can be started: 38021. Task created by **request.agent.create**. 38032. Download tasks that are created by **request.agent.create** but have failed or paused. 3804 3805**Required permissions**: ohos.permission.INTERNET 3806 3807**Atomic service API**: This API can be used in atomic services since API version 11. 3808 3809**System capability**: SystemCapability.Request.FileTransferAgent 3810 3811**Return value** 3812 3813| Type | Description | 3814| ------------------- | ------------------------- | 3815| Promise<void> | Promise that returns no value.| 3816 3817**Error codes** 3818 3819For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3820 3821| ID| Error Message| 3822| -------- | -------- | 3823| 201 | Permission denied. | 3824| 13400003 | task service ability error. | 3825| 21900007 | task state error. | 3826 3827**Example** 3828 3829 ```ts 3830 import { BusinessError } from '@kit.BasicServicesKit'; 3831 3832 let config: request.agent.Config = { 3833 action: request.agent.Action.DOWNLOAD, 3834 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3835 title: 'taskStartTest', 3836 description: 'Sample code for start the download task', 3837 mode: request.agent.Mode.BACKGROUND, 3838 overwrite: false, 3839 method: "GET", 3840 data: "", 3841 saveas: "./", 3842 network: request.agent.Network.CELLULAR, 3843 metered: false, 3844 roaming: true, 3845 retry: true, 3846 redirect: true, 3847 index: 0, 3848 begins: 0, 3849 ends: -1, 3850 gauge: false, 3851 precise: false, 3852 token: "it is a secret" 3853 }; 3854 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3855 task.start().then(() => { 3856 console.info(`Succeeded in starting a download task.`); 3857 }).catch((err: BusinessError) => { 3858 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3859 }); 3860 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3861 }).catch((err: BusinessError) => { 3862 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3863 }); 3864 ``` 3865 3866> **NOTE** 3867> 3868> 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). 3869 3870### pause<sup>10+</sup> 3871 3872pause(callback: AsyncCallback<void>): void 3873 3874Pauses a task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result. 3875 3876**System capability**: SystemCapability.Request.FileTransferAgent 3877 3878**Parameters** 3879 3880| Name| Type| Mandatory| Description| 3881| -------- | -------- | -------- | -------- | 3882| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3883 3884**Error codes** 3885 3886For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3887 3888| ID| Error Message| 3889| -------- | -------- | 3890| 13400003 | task service ability error. | 3891| 21900007 | task state error. | 3892 3893**Example** 3894 3895 ```ts 3896 import { BusinessError } from '@kit.BasicServicesKit'; 3897 3898 let config: request.agent.Config = { 3899 action: request.agent.Action.DOWNLOAD, 3900 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3901 title: 'taskPauseTest', 3902 description: 'Sample code for pause the download task', 3903 mode: request.agent.Mode.BACKGROUND, 3904 overwrite: false, 3905 method: "GET", 3906 data: "", 3907 saveas: "./", 3908 network: request.agent.Network.CELLULAR, 3909 metered: false, 3910 roaming: true, 3911 retry: true, 3912 redirect: true, 3913 index: 0, 3914 begins: 0, 3915 ends: -1, 3916 gauge: false, 3917 precise: false, 3918 token: "it is a secret" 3919 }; 3920 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3921 task.start(); 3922 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3923 task.pause((err: BusinessError) => { 3924 if (err) { 3925 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3926 return; 3927 } 3928 console.info(`Succeeded in pausing a download task. `); 3929 }); 3930 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3931 }).catch((err: BusinessError) => { 3932 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3933 }); 3934 ``` 3935 3936### pause<sup>10+</sup> 3937 3938pause(): Promise<void> 3939 3940Pauses a task that is waiting, running, or retrying. This API uses a promise to return the result. 3941 3942**System capability**: SystemCapability.Request.FileTransferAgent 3943 3944**Return value** 3945 3946| Type | Description | 3947| ------------------- | ------------------------- | 3948| Promise<void> | Promise that returns no value.| 3949 3950**Error codes** 3951 3952For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3953 3954| ID| Error Message| 3955| -------- | -------- | 3956| 13400003 | task service ability error. | 3957| 21900007 | task state error. | 3958 3959**Example** 3960 3961 ```ts 3962 import { BusinessError } from '@kit.BasicServicesKit'; 3963 3964 let config: request.agent.Config = { 3965 action: request.agent.Action.DOWNLOAD, 3966 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3967 title: 'taskPauseTest', 3968 description: 'Sample code for pause the download task', 3969 mode: request.agent.Mode.BACKGROUND, 3970 overwrite: false, 3971 method: "GET", 3972 data: "", 3973 saveas: "./", 3974 network: request.agent.Network.CELLULAR, 3975 metered: false, 3976 roaming: true, 3977 retry: true, 3978 redirect: true, 3979 index: 0, 3980 begins: 0, 3981 ends: -1, 3982 gauge: false, 3983 precise: false, 3984 token: "it is a secret" 3985 }; 3986 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3987 task.start(); 3988 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3989 task.pause().then(() => { 3990 console.info(`Succeeded in pausing a download task. `); 3991 }).catch((err: BusinessError) => { 3992 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3993 }); 3994 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3995 }).catch((err: BusinessError) => { 3996 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3997 }); 3998 ``` 3999 4000### resume<sup>10+</sup> 4001 4002resume(callback: AsyncCallback<void>): void 4003 4004Resumes a paused task. This API uses an asynchronous callback to return the result. 4005 4006**Required permissions**: ohos.permission.INTERNET 4007 4008**System capability**: SystemCapability.Request.FileTransferAgent 4009 4010**Parameters** 4011 4012| Name| Type| Mandatory| Description| 4013| -------- | -------- | -------- | -------- | 4014| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4015 4016**Error codes** 4017 4018For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4019 4020| ID| Error Message| 4021| -------- | -------- | 4022| 201 | Permission denied. | 4023| 13400003 | task service ability error. | 4024| 21900007 | task state error. | 4025 4026**Example** 4027 4028 ```ts 4029 import { BusinessError } from '@kit.BasicServicesKit'; 4030 4031 let config: request.agent.Config = { 4032 action: request.agent.Action.DOWNLOAD, 4033 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4034 title: 'taskResumeTest', 4035 description: 'Sample code for resume the download task', 4036 mode: request.agent.Mode.BACKGROUND, 4037 overwrite: false, 4038 method: "GET", 4039 data: "", 4040 saveas: "./", 4041 network: request.agent.Network.CELLULAR, 4042 metered: false, 4043 roaming: true, 4044 retry: true, 4045 redirect: true, 4046 index: 0, 4047 begins: 0, 4048 ends: -1, 4049 gauge: false, 4050 precise: false, 4051 token: "it is a secret" 4052 }; 4053 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4054 task.start(); 4055 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4056 task.pause(); 4057 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4058 task.resume((err: BusinessError) => { 4059 if (err) { 4060 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4061 return; 4062 } 4063 console.info(`Succeeded in resuming a download task. `); 4064 }); 4065 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4066 }).catch((err: BusinessError) => { 4067 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4068 }); 4069 ``` 4070 4071### resume<sup>10+</sup> 4072 4073resume(): Promise<void> 4074 4075Resumes a paused task. This API uses a promise to return the result. 4076 4077**Required permissions**: ohos.permission.INTERNET 4078 4079**System capability**: SystemCapability.Request.FileTransferAgent 4080 4081**Return value** 4082 4083| Type | Description | 4084| ------------------- | ------------------------- | 4085| Promise<void> | Promise that returns no value.| 4086 4087**Error codes** 4088 4089For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4090 4091| ID| Error Message| 4092| -------- | -------- | 4093| 201 | Permission denied. | 4094| 13400003 | task service ability error. | 4095| 21900007 | task state error. | 4096 4097**Example** 4098 4099 ```ts 4100 import { BusinessError } from '@kit.BasicServicesKit'; 4101 4102 let config: request.agent.Config = { 4103 action: request.agent.Action.DOWNLOAD, 4104 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4105 title: 'taskResumeTest', 4106 description: 'Sample code for resume the download task', 4107 mode: request.agent.Mode.BACKGROUND, 4108 overwrite: false, 4109 method: "GET", 4110 data: "", 4111 saveas: "./", 4112 network: request.agent.Network.CELLULAR, 4113 metered: false, 4114 roaming: true, 4115 retry: true, 4116 redirect: true, 4117 index: 0, 4118 begins: 0, 4119 ends: -1, 4120 gauge: false, 4121 precise: false, 4122 token: "it is a secret" 4123 }; 4124 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4125 task.start(); 4126 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4127 task.pause(); 4128 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4129 task.resume().then(() => { 4130 console.info(`Succeeded in resuming a download task. `); 4131 }).catch((err: BusinessError) => { 4132 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4133 }); 4134 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4135 }).catch((err: BusinessError) => { 4136 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4137 }); 4138 ``` 4139 4140### stop<sup>10+</sup> 4141 4142stop(callback: AsyncCallback<void>): void 4143 4144Stops 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. 4145 4146**Atomic service API**: This API can be used in atomic services since API version 11. 4147 4148**System capability**: SystemCapability.Request.FileTransferAgent 4149 4150**Parameters** 4151 4152| Name| Type| Mandatory| Description| 4153| -------- | -------- | -------- | -------- | 4154| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4155 4156**Error codes** 4157 4158For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4159 4160| ID| Error Message| 4161| -------- | -------- | 4162| 13400003 | task service ability error. | 4163| 21900007 | task state error. | 4164 4165**Example** 4166 4167 ```ts 4168 import { BusinessError } from '@kit.BasicServicesKit'; 4169 4170 let config: request.agent.Config = { 4171 action: request.agent.Action.DOWNLOAD, 4172 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4173 title: 'taskStopTest', 4174 description: 'Sample code for stop the download task', 4175 mode: request.agent.Mode.BACKGROUND, 4176 overwrite: false, 4177 method: "GET", 4178 data: "", 4179 saveas: "./", 4180 network: request.agent.Network.CELLULAR, 4181 metered: false, 4182 roaming: true, 4183 retry: true, 4184 redirect: true, 4185 index: 0, 4186 begins: 0, 4187 ends: -1, 4188 gauge: false, 4189 precise: false, 4190 token: "it is a secret" 4191 }; 4192 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4193 task.start(); 4194 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4195 task.stop((err: BusinessError) => { 4196 if (err) { 4197 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4198 return; 4199 } 4200 console.info(`Succeeded in stopping a download task. `); 4201 }); 4202 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4203 }).catch((err: BusinessError) => { 4204 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4205 }); 4206 ``` 4207 4208 4209### stop<sup>10+</sup> 4210 4211stop(): Promise<void> 4212 4213Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. 4214 4215**Atomic service API**: This API can be used in atomic services since API version 11. 4216 4217**System capability**: SystemCapability.Request.FileTransferAgent 4218 4219**Return value** 4220 4221| Type | Description | 4222| ------------------- | ------------------------- | 4223| Promise<void> | Promise that returns no value.| 4224 4225**Error codes** 4226 4227For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4228 4229| ID| Error Message| 4230| -------- | -------- | 4231| 13400003 | task service ability error. | 4232| 21900007 | task state error. | 4233 4234**Example** 4235 4236 ```ts 4237 import { BusinessError } from '@kit.BasicServicesKit'; 4238 4239 let config: request.agent.Config = { 4240 action: request.agent.Action.DOWNLOAD, 4241 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4242 title: 'taskStopTest', 4243 description: 'Sample code for stop the download task', 4244 mode: request.agent.Mode.BACKGROUND, 4245 overwrite: false, 4246 method: "GET", 4247 data: "", 4248 saveas: "./", 4249 network: request.agent.Network.CELLULAR, 4250 metered: false, 4251 roaming: true, 4252 retry: true, 4253 redirect: true, 4254 index: 0, 4255 begins: 0, 4256 ends: -1, 4257 gauge: false, 4258 precise: false, 4259 token: "it is a secret" 4260 }; 4261 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4262 task.start(); 4263 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4264 task.stop().then(() => { 4265 console.info(`Succeeded in stopping a download task. `); 4266 }).catch((err: BusinessError) => { 4267 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4268 }); 4269 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4270 }).catch((err: BusinessError) => { 4271 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4272 }); 4273 ``` 4274 4275### setMaxSpeed<sup>18+</sup> 4276 4277setMaxSpeed(speed: number): Promise\<void\> 4278 4279Sets the maximum number of bytes that can be transmitted by a task per second. This API uses a promise to return the result. 4280 4281**System capability**: SystemCapability.Request.FileTransferAgent 4282 4283**Parameters** 4284 4285| Name | Type | Mandatory| Description | 4286|-------|--------|----|------------------------------------| 4287| speed | number | Yes | Maximum number of bytes that can be transmitted by a task per second, with a minimum of 16384 bytes.| 4288 4289**Return value** 4290 4291| Type | Description | 4292|-----------------|----------------------------| 4293| Promise<void> | Promise that returns no value.| 4294 4295**Error codes** 4296 4297For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4298 4299| ID | Error Message | 4300|----------|--------------------------------------------------------------------------------------------------------------------------------| 4301| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed.. | 4302| 13400003 | task service ability error. | 4303 4304**Example** 4305 4306 ```ts 4307 import { BusinessError } from '@kit.BasicServicesKit'; 4308 4309 let config: request.agent.Config = { 4310 action: request.agent.Action.DOWNLOAD, 4311 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4312 saveas: "./", 4313 }; 4314 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4315 // Set the maximum transmission speed. 4316 task.setMaxSpeed(10 * 1024 * 1024).then(() => { 4317 console.info(`Succeeded in setting the max speed of the task. result: ${task.tid}`); 4318 }).catch((err: BusinessError) => { 4319 console.error(`Failed to set the max speed of the task. result: ${task.tid}`); 4320 }); 4321 }).catch((err: BusinessError) => { 4322 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4323 }); 4324 ``` 4325 4326## request.agent.create<sup>10+</sup> 4327 4328create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void 4329 4330Creates an upload or download task and adds it to the queue. This API uses an asynchronous callback to return a result. HTTP is supported. 4331 4332 4333**Required permissions**: ohos.permission.INTERNET 4334 4335**Atomic service API**: This API can be used in atomic services since API version 11. 4336 4337**System capability**: SystemCapability.Request.FileTransferAgent 4338 4339**Parameters** 4340 4341| Name| Type| Mandatory| Description| 4342| -------- | -------- | -------- | -------- | 4343| config | [Config](#config10) | Yes| Task configuration.| 4344| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4345| 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.| 4346 4347**Error codes** 4348 4349For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4350 4351| ID| Error Message| 4352| -------- | -------- | 4353| 201 | permission denied. | 4354| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4355| 13400001 | file operation error. | 4356| 13400003 | task service ability error. | 4357| 21900004 | the application task queue is full. | 4358| 21900005 | task mode error. | 4359 4360**Example** 4361 4362 ```ts 4363 import { BusinessError } from '@kit.BasicServicesKit'; 4364 4365 let attachments: Array<request.agent.FormItem> = [{ 4366 name: "createTest", 4367 value: { 4368 filename: "createTest.avi", 4369 mimeType: "application/octet-stream", 4370 path: "./createTest.avi", 4371 } 4372 }]; 4373 let config: request.agent.Config = { 4374 action: request.agent.Action.UPLOAD, 4375 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4376 title: 'createTest', 4377 description: 'Sample code for create task', 4378 mode: request.agent.Mode.BACKGROUND, 4379 overwrite: false, 4380 method: "PUT", 4381 data: attachments, 4382 saveas: "./", 4383 network: request.agent.Network.CELLULAR, 4384 metered: false, 4385 roaming: true, 4386 retry: true, 4387 redirect: true, 4388 index: 0, 4389 begins: 0, 4390 ends: -1, 4391 gauge: false, 4392 precise: false, 4393 token: "it is a secret" 4394 }; 4395 request.agent.create(getContext(), config, async (err: BusinessError, task: request.agent.Task) => { 4396 if (err) { 4397 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4398 return; 4399 } 4400 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4401 await task.start(); 4402 // You need to manually call remove() to end the lifecycle of the task object. 4403 request.agent.remove(task.tid); 4404 }); 4405 ``` 4406 4407> **NOTE** 4408> 4409> 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). 4410 4411## request.agent.create<sup>10+</sup> 4412 4413create(context: BaseContext, config: Config): Promise<Task> 4414 4415Creates an upload or download task and adds it to the queue. This API uses a promise to return the result. HTTP is supported. 4416 4417 4418**Required permissions**: ohos.permission.INTERNET 4419 4420**Atomic service API**: This API can be used in atomic services since API version 11. 4421 4422**System capability**: SystemCapability.Request.FileTransferAgent 4423 4424**Parameters** 4425 4426| Name| Type| Mandatory| Description| 4427| -------- | -------- | -------- | -------- | 4428| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4429| config | [Config](#config10) | Yes| Task configuration.| 4430 4431**Return value** 4432 4433| Type | Description | 4434| ------------------- | ------------------------- | 4435| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4436 4437**Error codes** 4438 4439For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4440 4441| ID| Error Message| 4442| -------- | -------- | 4443| 201 | permission denied. | 4444| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4445| 13400001 | file operation error. | 4446| 13400003 | task service ability error. | 4447| 21900004 | the application task queue is full. | 4448| 21900005 | task mode error. | 4449 4450**Example** 4451 4452 ```ts 4453 import { BusinessError } from '@kit.BasicServicesKit'; 4454 4455 let attachments: Array<request.agent.FormItem> = [{ 4456 name: "createTest", 4457 value: { 4458 filename: "createTest.avi", 4459 mimeType: "application/octet-stream", 4460 path: "./createTest.avi", 4461 } 4462 }]; 4463 let config: request.agent.Config = { 4464 action: request.agent.Action.UPLOAD, 4465 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4466 title: 'createTest', 4467 description: 'Sample code for create task', 4468 mode: request.agent.Mode.BACKGROUND, 4469 overwrite: false, 4470 method: "PUT", 4471 data: attachments, 4472 saveas: "./", 4473 network: request.agent.Network.CELLULAR, 4474 metered: false, 4475 roaming: true, 4476 retry: true, 4477 redirect: true, 4478 index: 0, 4479 begins: 0, 4480 ends: -1, 4481 gauge: false, 4482 precise: false, 4483 token: "it is a secret" 4484 }; 4485 request.agent.create(getContext(), config).then(async (task: request.agent.Task) => { 4486 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4487 await task.start(); 4488 // You need to manually call remove() to end the lifecycle of the task object. 4489 request.agent.remove(task.tid); 4490 }).catch((err: BusinessError) => { 4491 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4492 }); 4493 ``` 4494 4495> **NOTE** 4496> 4497> 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). 4498 4499## request.agent.getTask<sup>11+</sup> 4500 4501getTask(context: BaseContext, id: string, token?: string): Promise<Task> 4502 4503Obtains task information based on the task ID. This API uses a promise to return the result. 4504 4505**System capability**: SystemCapability.Request.FileTransferAgent 4506 4507**Parameters** 4508 4509| Name| Type| Mandatory| Description| 4510| -------- | -------- | -------- | -------- | 4511| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4512| id | string | Yes| Task ID.| 4513| token | string | No| Token for task query.| 4514 4515**Return value** 4516 4517| Type | Description | 4518| ------------------- | ------------------------- | 4519| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4520 4521**Error codes** 4522 4523For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4524 4525| ID| Error Message| 4526| -------- | -------- | 4527| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4528| 13400003 | task service ability error. | 4529| 21900006 | task not found. | 4530 4531**Example** 4532 4533 ```ts 4534 import { BusinessError } from '@kit.BasicServicesKit'; 4535 4536 request.agent.getTask(getContext(), "123456").then((task: request.agent.Task) => { 4537 console.info(`Succeeded in querying a task. result: ${task.tid}`); 4538 }).catch((err: BusinessError) => { 4539 console.error(`Failed to query a task, Code: ${err.code}, message: ${err.message}`); 4540 }); 4541 ``` 4542 4543## request.agent.remove<sup>10+</sup> 4544 4545remove(id: string, callback: AsyncCallback<void>): void 4546 4547Removes 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. 4548 4549**Atomic service API**: This API can be used in atomic services since API version 11. 4550 4551**System capability**: SystemCapability.Request.FileTransferAgent 4552 4553**Parameters** 4554 4555| Name| Type| Mandatory| Description| 4556| -------- | -------- | -------- | -------- | 4557| id | string | Yes| Task ID.| 4558| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4559 4560**Error codes** 4561 4562For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4563 4564| ID| Error Message| 4565| -------- | -------- | 4566| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. | 4567| 13400003 | task service ability error. | 4568| 21900006 | task not found. | 4569 4570**Example** 4571 4572 ```ts 4573 import { BusinessError } from '@kit.BasicServicesKit'; 4574 4575 request.agent.remove("123456", (err: BusinessError) => { 4576 if (err) { 4577 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4578 return; 4579 } 4580 console.info(`Succeeded in creating a download task.`); 4581 }); 4582 ``` 4583 4584 4585## request.agent.remove<sup>10+</sup> 4586 4587remove(id: string): Promise<void> 4588 4589Removes 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. 4590 4591**Atomic service API**: This API can be used in atomic services since API version 11. 4592 4593**System capability**: SystemCapability.Request.FileTransferAgent 4594 4595**Parameters** 4596 4597| Name| Type| Mandatory| Description| 4598| -------- | -------- | -------- | -------- | 4599| id | string | Yes| Task ID.| 4600 4601**Return value** 4602 4603| Type | Description | 4604| ------------------- | ------------------------- | 4605| Promise<void> | Promise that returns no value.| 4606 4607**Error codes** 4608 4609For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4610 4611| ID| Error Message| 4612| -------- | -------- | 4613| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. | 4614| 13400003 | task service ability error. | 4615| 21900006 | task not found. | 4616 4617**Example** 4618 4619 ```ts 4620 import { BusinessError } from '@kit.BasicServicesKit'; 4621 4622 request.agent.remove("123456").then(() => { 4623 console.info(`Succeeded in removing a download task. `); 4624 }).catch((err: BusinessError) => { 4625 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4626 }); 4627 ``` 4628 4629 4630## request.agent.show<sup>10+</sup> 4631 4632show(id: string, callback: AsyncCallback<TaskInfo>): void 4633 4634Queries a task details based on the task ID. This API uses an asynchronous callback to return the result. 4635 4636**System capability**: SystemCapability.Request.FileTransferAgent 4637 4638**Parameters** 4639 4640| Name| Type| Mandatory| Description| 4641| -------- | -------- | -------- | -------- | 4642| id | string | Yes| Task ID.| 4643| 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.| 4644 4645**Error codes** 4646 4647For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4648 4649| ID| Error Message| 4650| -------- | -------- | 4651| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. | 4652| 13400003 | task service ability error. | 4653| 21900006 | task not found. | 4654 4655**Example** 4656 4657 ```ts 4658 import { BusinessError } from '@kit.BasicServicesKit'; 4659 4660 request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4661 if (err) { 4662 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4663 return; 4664 } 4665 console.info(`Succeeded in showing a upload task.`); 4666 }); 4667 ``` 4668 4669 4670## request.agent.show<sup>10+</sup> 4671 4672show(id: string): Promise<TaskInfo> 4673 4674Queries a task details based on the task ID. This API uses a promise to return the result. 4675 4676**System capability**: SystemCapability.Request.FileTransferAgent 4677 4678**Parameters** 4679 4680| Name| Type| Mandatory| Description| 4681| -------- | -------- | -------- | -------- | 4682| id | string | Yes| Task ID.| 4683 4684**Return value** 4685 4686| Type | Description | 4687| ------------------- | ------------------------- | 4688| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4689 4690**Error codes** 4691 4692For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4693 4694| ID| Error Message| 4695| -------- | -------- | 4696| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. | 4697| 13400003 | task service ability error. | 4698| 21900006 | task not found. | 4699 4700**Example** 4701 4702 ```ts 4703 import { BusinessError } from '@kit.BasicServicesKit'; 4704 4705 request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => { 4706 console.info(`Succeeded in showing a upload task.`); 4707 }).catch((err: BusinessError) => { 4708 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4709 }); 4710 ``` 4711 4712 4713## request.agent.touch<sup>10+</sup> 4714 4715touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void 4716 4717Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result. 4718 4719**System capability**: SystemCapability.Request.FileTransferAgent 4720 4721**Parameters** 4722 4723| Name| Type| Mandatory| Description| 4724| -------- | -------- | -------- | -------- | 4725| id | string | Yes| Task ID.| 4726| token | string | Yes| Token for task query.| 4727| 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.| 4728 4729**Error codes** 4730 4731For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4732 4733| ID| Error Message| 4734| -------- | -------- | 4735| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4736| 13400003 | task service ability error. | 4737| 21900006 | task not found. | 4738 4739**Example** 4740 4741 ```ts 4742 import { BusinessError } from '@kit.BasicServicesKit'; 4743 4744 request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4745 if (err) { 4746 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4747 return; 4748 } 4749 console.info(`Succeeded in touching a upload task.`); 4750 }); 4751 ``` 4752 4753 4754## request.agent.touch<sup>10+</sup> 4755 4756touch(id: string, token: string): Promise<TaskInfo> 4757 4758Queries the task details based on the task ID and token. This API uses a promise to return the result. 4759 4760**System capability**: SystemCapability.Request.FileTransferAgent 4761 4762**Parameters** 4763 4764| Name| Type| Mandatory| Description| 4765| -------- | -------- | -------- | -------- | 4766| id | string | Yes| Task ID.| 4767| token | string | Yes| Token for task query.| 4768 4769**Return value** 4770 4771| Type | Description | 4772| ------------------- | ------------------------- | 4773| Promise<[TaskInfo](#taskinfo10)> | Promise used to return the **TaskInfo** object.| 4774 4775**Error codes** 4776 4777For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4778 4779| ID| Error Message| 4780| -------- | -------- | 4781| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4782| 13400003 | task service ability error. | 4783| 21900006 | task not found. | 4784 4785**Example** 4786 4787 ```ts 4788 import { BusinessError } from '@kit.BasicServicesKit'; 4789 4790 request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { 4791 console.info(`Succeeded in touching a upload task. `); 4792 }).catch((err: BusinessError) => { 4793 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4794 }); 4795 ``` 4796 4797## request.agent.search<sup>10+</sup> 4798 4799search(callback: AsyncCallback<Array<string>>): void 4800 4801Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4802 4803**System capability**: SystemCapability.Request.FileTransferAgent 4804 4805**Parameters** 4806 4807| Name| Type| Mandatory| Description| 4808| -------- | -------- | -------- | -------- | 4809| 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.| 4810 4811**Error codes** 4812 4813For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4814 4815| ID| Error Message| 4816| -------- | -------- | 4817| 401 | parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed. | 4818| 13400003 | task service ability error. | 4819 4820**Example** 4821 4822 ```ts 4823 import { BusinessError } from '@kit.BasicServicesKit'; 4824 4825 request.agent.search((err: BusinessError, data: Array<string>) => { 4826 if (err) { 4827 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4828 return; 4829 } 4830 console.info(`Succeeded in searching a upload task. `); 4831 }); 4832 ``` 4833 4834## request.agent.search<sup>10+</sup> 4835 4836search(filter: Filter, callback: AsyncCallback<Array<string>>): void 4837 4838Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4839 4840**System capability**: SystemCapability.Request.FileTransferAgent 4841 4842**Parameters** 4843 4844| Name| Type| Mandatory| Description| 4845| -------- | -------- | -------- | -------- | 4846| filter | [Filter](#filter10) | Yes| Filter criteria.| 4847| 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.| 4848 4849**Error codes** 4850 4851For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4852 4853| ID| Error Message| 4854| -------- | -------- | 4855| 401 | parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed. | 4856| 13400003 | task service ability error. | 4857 4858**Example** 4859 4860 ```ts 4861 import { BusinessError } from '@kit.BasicServicesKit'; 4862 4863 let filter: request.agent.Filter = { 4864 action: request.agent.Action.UPLOAD, 4865 mode: request.agent.Mode.BACKGROUND 4866 } 4867 request.agent.search(filter, (err: BusinessError, data: Array<string>) => { 4868 if (err) { 4869 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4870 return; 4871 } 4872 console.info(`Succeeded in searching a upload task. `); 4873 }); 4874 ``` 4875 4876 4877## request.agent.search<sup>10+</sup> 4878 4879search(filter?: Filter): Promise<Array<string>> 4880 4881Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. 4882 4883**System capability**: SystemCapability.Request.FileTransferAgent 4884 4885**Parameters** 4886 4887| Name| Type| Mandatory| Description| 4888| -------- | -------- | -------- | -------- | 4889| filter | [Filter](#filter10) | No| Filter criteria.| 4890 4891**Return value** 4892 4893| Type | Description | 4894| ------------------- | ------------------------- | 4895| Promise<Array<string>> | Promise Promise used to return task ID matches.| 4896 4897**Error codes** 4898 4899For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4900 4901| ID| Error Message| 4902| -------- | -------- | 4903| 401 | parameter error. Possible causes: 1. Incorrect parameter type. 2. Parameter verification failed. | 4904| 13400003 | task service ability error. | 4905 4906**Example** 4907 4908 ```ts 4909 import { BusinessError } from '@kit.BasicServicesKit'; 4910 4911 let filter: request.agent.Filter = { 4912 action: request.agent.Action.UPLOAD, 4913 mode: request.agent.Mode.BACKGROUND 4914 } 4915 request.agent.search(filter).then((data: Array<string>) => { 4916 console.info(`Succeeded in searching a upload task. `); 4917 }).catch((err: BusinessError) => { 4918 console.error(`Failed to search a upload task, Code: ${err.code}, message: ${err.message}`); 4919 }); 4920 ``` 4921 4922## request.agent.createGroup<sup>15+</sup> 4923 4924createGroup(config: GroupConfig): Promise\<string\> 4925 4926Creates a group based on [GroupConfig<sup>15+</sup>](#groupconfig15) and returns the group ID. This API uses a promise to return the result. 4927 4928**System capability**: SystemCapability.Request.FileTransferAgent 4929 4930**Parameters** 4931 4932| Name | Type | Mandatory| Description | 4933|--------|---------------------------------------------|----|-----------| 4934| config | [GroupConfig<sup>15+</sup>](#groupconfig15) | Yes | Group options for a download task.| 4935 4936**Return value** 4937 4938| Type | Description | 4939|-------------------|----------------------------------| 4940| Promise\<string\> | Promise used to return the result.| 4941 4942**Error codes** 4943 4944For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4945 4946| ID | Error Message | 4947|----------|------------------------------------------------------------------------------------------------| 4948| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4949| 13400003 | task service ability error. | 4950 4951**Example** 4952 4953 ```ts 4954 import { BusinessError } from '@kit.BasicServicesKit'; 4955 4956 // Prepare the GroupConfig object. 4957 let config: request.agent.GroupConfig = { 4958 notification: {}, 4959 }; 4960 // Call the createGroup API to create a group. 4961 request.agent.createGroup(config).then((gid: string) => { 4962 console.info(`Succeeded in creating a download task group. `); 4963 }).catch((err: BusinessError) => { 4964 console.error(`Failed to create a download group, Code: ${err.code}, message: ${err.message}`); 4965 }); 4966 ``` 4967 4968## request.agent.attachGroup<sup>15+</sup> 4969 4970attachGroup(gid: string, tids: string[]): Promise\<void\> 4971 4972Attaches multiple download task IDs to a specified group ID. This API uses a promise to return the result. 4973 4974If any task ID does not meet the attachment conditions, all tasks in the list will not be added to the group. 4975 4976**System capability**: SystemCapability.Request.FileTransferAgent 4977 4978**Parameters** 4979 4980| Name | Type | Mandatory| Description | 4981|------|----------|----|---------------------| 4982| gid | string | Yes | Target group ID. | 4983| tids | string[] | Yes | List of task IDs to attach.| 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. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 4998| 13400003 | task service ability error | 4999| 21900005 | task mode error | 5000| 21900006 | task not found | 5001| 21900007 | task state error | 5002| 21900008 | group deleted or not found | 5003 5004**Example** 5005 5006 ```ts 5007 import { BusinessError } from '@kit.BasicServicesKit'; 5008 5009 // Prepare the group ID and task ID list. 5010 let groupId: string = "123456789"; 5011 let taskIds: string[] = ["1111", "2222", "3333", "4444"]; 5012 // Call the attachGroup API to add a task ID list to the group. 5013 request.agent.attachGroup(groupId, taskIds).then(() => { 5014 console.info(`Succeeded in attaching tasks to the download task group.`); 5015 }).catch((err: BusinessError) => { 5016 console.error(`Failed to attach tasks to the download group, Code: ${err.code}, message: ${err.message}`); 5017 }); 5018 ``` 5019 5020## request.agent.deleteGroup<sup>15+</sup> 5021 5022deleteGroup(gid: string): Promise\<void\> 5023 5024Deletes a specified group. No task can be added to the group. This API uses a promise to return the result. 5025 5026When 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. 5027 5028**System capability**: SystemCapability.Request.FileTransferAgent 5029 5030**Parameters** 5031 5032| Name | Type | Mandatory| Description | 5033|------|----------|----|---------| 5034| gid | string | Yes | Target group ID.| 5035 5036**Return value** 5037 5038| Type | Description | 5039|-----------------|------------| 5040| Promise<void> | Promise that returns no value.| 5041 5042**Error codes** 5043 5044For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 5045 5046| ID | Error Message | 5047|----------|------------------------------------------------------------------------------------------------| 5048| 401 | parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | 5049| 13400003 | task service ability error | 5050| 21900008 | group deleted or not found | 5051 5052**Example** 5053 5054 ```ts 5055 import { BusinessError } from '@kit.BasicServicesKit'; 5056 5057 // Prepare the group ID. 5058 let groupId: string = "123456789"; 5059 5060 // Call the deleteGroup API to delete a group. 5061 request.agent.deleteGroup(groupId).then(() => { 5062 console.info(`Succeeded in deleting the download task group.`); 5063 }).catch((err: BusinessError) => { 5064 console.error(`Failed to delete the download group, Code: ${err.code}, message: ${err.message}`); 5065 }); 5066 ``` 5067