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### Network Types 22You can set **networkType** in [DownloadConfig](#downloadconfig) to specify the network type for the download service. 23 24| Name| Type| Value| Description| 25| -------- | -------- | -------- | -------- | 26| NETWORK_MOBILE | number | 0x00000001 | Whether download is allowed on a mobile network.| 27| NETWORK_WIFI | number | 0x00010000 | Whether download is allowed on a WLAN.| 28 29### Download Error Codes 30The table below lists the values of **err** in the callback of [on('fail')<sup>7+</sup>](#onfail7) and the values of **failedReason** returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9). 31 32| Name| Type| Value| Description| 33| -------- | -------- | -------- | -------- | 34| ERROR_CANNOT_RESUME<sup>7+</sup> | number | 0 | Failure to resume the download due to network errors.| 35| ERROR_DEVICE_NOT_FOUND<sup>7+</sup> | number | 1 | Failure to find a storage device such as a memory card.| 36| ERROR_FILE_ALREADY_EXISTS<sup>7+</sup> | number | 2 | Failure to download the file because it already exists.| 37| ERROR_FILE_ERROR<sup>7+</sup> | number | 3 | File operation failure.| 38| ERROR_HTTP_DATA_ERROR<sup>7+</sup> | number | 4 | HTTP transmission failure.| 39| ERROR_INSUFFICIENT_SPACE<sup>7+</sup> | number | 5 | Insufficient storage space.| 40| ERROR_TOO_MANY_REDIRECTS<sup>7+</sup> | number | 6 | Error caused by too many network redirections.| 41| ERROR_UNHANDLED_HTTP_CODE<sup>7+</sup> | number | 7 | Unidentified HTTP code.| 42| ERROR_UNKNOWN<sup>7+</sup> | number | 8 | Unknown error.| 43| ERROR_OFFLINE<sup>9+</sup> | number | 9 | No network connection.| 44| ERROR_UNSUPPORTED_NETWORK_TYPE<sup>9+</sup> | number | 10 | Network type mismatch.| 45 46> **NOTE** 47> 48> 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. 49 50### Causes of Download Pause 51The table below lists the values of **pausedReason** returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9). 52 53| Name| Type| Value| Description| 54| -------- | -------- | -------- | -------- | 55| PAUSED_QUEUED_FOR_WIFI<sup>7+</sup> | number | 0 | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| 56| PAUSED_WAITING_FOR_NETWORK<sup>7+</sup> | number | 1 | Download paused due to a network connection problem, for example, network disconnection.| 57| PAUSED_WAITING_TO_RETRY<sup>7+</sup> | number | 2 | Download paused and then retried.| 58| PAUSED_BY_USER<sup>9+</sup> | number | 3 | The user paused the session.| 59| PAUSED_UNKNOWN<sup>7+</sup> | number | 4 | Download paused due to unknown reasons.| 60 61### Download Task Status Codes 62The table below lists the values of **status** returned by [getTaskInfo<sup>9+</sup>](#gettaskinfo9). 63 64| Name| Type| Value| Description| 65| -------- | -------- | -------- | -------- | 66| SESSION_SUCCESSFUL<sup>7+</sup> | number | 0 | Successful download.| 67| SESSION_RUNNING<sup>7+</sup> | number | 1 | Download in progress.| 68| SESSION_PENDING<sup>7+</sup> | number | 2 | Download pending.| 69| SESSION_PAUSED<sup>7+</sup> | number | 3 | Download paused.| 70| SESSION_FAILED<sup>7+</sup> | number | 4 | Download failure without retry.| 71 72 73## request.uploadFile<sup>9+</sup> 74 75uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> 76 77Uploads files. This API uses a promise to return the result. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information. 78 79**Required permissions**: ohos.permission.INTERNET 80 81**System capability**: SystemCapability.MiscServices.Upload 82 83**Parameters** 84 85| Name| Type| Mandatory| Description| 86| -------- | -------- | -------- | -------- | 87| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 88| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 89 90 91**Return value** 92 93| Type| Description| 94| -------- | -------- | 95| Promise<[UploadTask](#uploadtask)> | Promise used to return the upload task.| 96 97**Error codes** 98 99For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 100 101| ID| Error Message| 102| -------- | -------- | 103| 201 | the permissions check fails | 104| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 105| 13400002 | bad file path. | 106 107**Example** 108 109 ```ts 110 import { BusinessError } from '@kit.BasicServicesKit'; 111 112 let uploadTask: request.UploadTask; 113 let uploadConfig: request.UploadConfig = { 114 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 115 header: { 'Accept': '*/*' }, 116 method: "POST", 117 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 118 data: [{ name: "name123", value: "123" }], 119 }; 120 try { 121 request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => { 122 uploadTask = data; 123 }).catch((err: BusinessError) => { 124 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 125 }); 126 } catch (err) { 127 console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`); 128 } 129 ``` 130 131> **NOTE** 132> 133> 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). 134 135 136## request.uploadFile<sup>9+</sup> 137 138uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void 139 140Uploads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information. 141 142**Required permissions**: ohos.permission.INTERNET 143 144**System capability**: SystemCapability.MiscServices.Upload 145 146**Parameters** 147 148| Name| Type| Mandatory| Description| 149| -------- | -------- | -------- | -------- | 150| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 151| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 152| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| 153 154**Error codes** 155 156For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 157 158| ID| Error Message| 159| -------- | -------- | 160| 201 | the permissions check fails | 161| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 162| 13400002 | bad file path. | 163 164**Example** 165 166 ```ts 167 import { BusinessError } from '@kit.BasicServicesKit'; 168 169 let uploadTask: request.UploadTask; 170 let uploadConfig: request.UploadConfig = { 171 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 172 header: { 'Accept': '*/*' }, 173 method: "POST", 174 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 175 data: [{ name: "name123", value: "123" }], 176 }; 177 try { 178 request.uploadFile(getContext(), uploadConfig, (err: BusinessError, data: request.UploadTask) => { 179 if (err) { 180 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 181 return; 182 } 183 uploadTask = data; 184 }); 185 } catch (err) { 186 console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`); 187 } 188 ``` 189 190> **NOTE** 191> 192> 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). 193 194## request.upload<sup>(deprecated)</sup> 195 196upload(config: UploadConfig): Promise<UploadTask> 197 198Uploads files. This API uses a promise to return the result. 199 200**Model restriction**: This API can be used only in the FA model. 201 202> **NOTE** 203> 204> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9) instead. 205 206**Required permissions**: ohos.permission.INTERNET 207 208**System capability**: SystemCapability.MiscServices.Upload 209 210**Parameters** 211 212| Name| Type| Mandatory| Description| 213| -------- | -------- | -------- | -------- | 214| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 215 216**Return value** 217 218| Type| Description| 219| -------- | -------- | 220| Promise<[UploadTask](#uploadtask)> | Promise used to return the upload task.| 221 222**Error codes** 223 224For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 225 226| ID| Error Message| 227| -------- | -------- | 228| 201 | the permissions check fails | 229 230**Example** 231 232 ```js 233 let uploadTask; 234 let uploadConfig = { 235 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 236 header: { 'Accept': '*/*' }, 237 method: "POST", 238 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 239 data: [{ name: "name123", value: "123" }], 240 }; 241 request.upload(uploadConfig).then((data) => { 242 uploadTask = data; 243 }).catch((err) => { 244 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 245 }) 246 ``` 247 248 249## request.upload<sup>(deprecated)</sup> 250 251upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void 252 253Uploads files. This API uses an asynchronous callback to return the result. 254 255**Model restriction**: This API can be used only in the FA model. 256 257> **NOTE** 258> 259> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1) instead. 260 261**Required permissions**: ohos.permission.INTERNET 262 263**System capability**: SystemCapability.MiscServices.Upload 264 265**Parameters** 266 267| Name| Type| Mandatory| Description| 268| -------- | -------- | -------- | -------- | 269| config | [UploadConfig](#uploadconfig6) | Yes| Upload configurations.| 270| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| 271 272**Error codes** 273 274For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 275 276| ID| Error Message| 277| -------- | -------- | 278| 201 | the permissions check fails | 279 280**Example** 281 282 ```js 283 let uploadTask; 284 let uploadConfig = { 285 url: 'http://www.example.com', // Replace the URL with the HTTP address of the real server. 286 header: { 'Accept': '*/*' }, 287 method: "POST", 288 files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], 289 data: [{ name: "name123", value: "123" }], 290 }; 291 request.upload(uploadConfig, (err, data) => { 292 if (err) { 293 console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`); 294 return; 295 } 296 uploadTask = data; 297 }); 298 ``` 299 300## UploadTask 301 302Implements 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. 303 304 305 306### on('progress') 307 308on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void 309 310Subscribes to upload progress events. This API uses a callback to return the result asynchronously. 311 312> **NOTE** 313> 314> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background. 315 316**System capability**: SystemCapability.MiscServices.Upload 317 318**Parameters** 319 320| Name| Type| Mandatory| Description| 321| -------- | -------- | -------- | -------- | 322| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| 323| callback | function | Yes| Callback for the upload progress event.| 324 325 Parameters of the callback function 326 327| Name| Type| Mandatory| Description| 328| -------- | -------- | -------- | -------- | 329| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| 330| totalSize | number | Yes| Total size of the files to upload, in bytes.| 331 332**Error codes** 333 334For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 335 336| ID| Error Message| 337| -------- | -------- | 338| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 339 340**Example** 341 342<!--code_no_check--> 343 ```ts 344 let upProgressCallback = (uploadedSize: number, totalSize: number) => { 345 console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); 346 }; 347 uploadTask.on('progress', upProgressCallback); 348 ``` 349 350 351### on('headerReceive')<sup>7+</sup> 352 353on(type: 'headerReceive', callback: (header: object) => void): void 354 355Subscribes to HTTP response events for the upload task. This API uses a callback to return the result asynchronously. 356 357**System capability**: SystemCapability.MiscServices.Upload 358 359**Parameters** 360 361| Name| Type| Mandatory| Description| 362| -------- | -------- | -------- | -------- | 363| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response received).| 364| callback | function | Yes| Callback for the HTTP response event.| 365 366 Parameters of the callback function 367 368| Name| Type| Mandatory| Description| 369| -------- | -------- | -------- | -------- | 370| header | object | Yes| HTTP response.| 371 372**Error codes** 373 374For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 375 376| ID| Error Message| 377| -------- | -------- | 378| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 379 380**Example** 381 382<!--code_no_check--> 383 ```ts 384 let headerCallback = (headers: object) => { 385 console.info("upOnHeader headers:" + JSON.stringify(headers)); 386 }; 387 uploadTask.on('headerReceive', headerCallback); 388 ``` 389 390 391### on('complete' | 'fail')<sup>9+</sup> 392 393 on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; 394 395Subscribes to upload completion or failure events. This API uses a callback to return the result asynchronously. 396 397**System capability**: SystemCapability.MiscServices.Upload 398 399**Parameters** 400 401| Name| Type| Mandatory| Description| 402| -------- | -------- | -------- | -------- | 403| 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.| 404| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| 405 406 Parameters of the callback function 407 408| Name| Type| Mandatory| Description| 409| -------- | -------- | -------- | -------- | 410| taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| 411 412**Error codes** 413 414For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 415 416| ID| Error Message| 417| -------- | -------- | 418| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 419 420**Example** 421 422<!--code_no_check--> 423 ```ts 424 let upCompleteCallback = (taskStates: Array<request.TaskState>) => { 425 for (let i = 0; i < taskStates.length; i++) { 426 console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); 427 } 428 }; 429 uploadTask.on('complete', upCompleteCallback); 430 431 let upFailCallback = (taskStates: Array<request.TaskState>) => { 432 for (let i = 0; i < taskStates.length; i++) { 433 console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); 434 } 435 }; 436 uploadTask.on('fail', upFailCallback); 437 ``` 438 439 440### off('progress') 441 442off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void 443 444Unsubscribes from upload progress events. 445 446**System capability**: SystemCapability.MiscServices.Upload 447 448**Parameters** 449 450| Name| Type| Mandatory| Description| 451| -------- | -------- | -------- | -------- | 452| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| 453| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.<br>**uploadedSize**: size of the uploaded files, in B.<br>**totalSize**: Total size of the files to upload, in B.| 454 455**Error codes** 456 457For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 458 459| ID| Error Message| 460| -------- | -------- | 461| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 462 463**Example** 464 465<!--code_no_check--> 466 ```ts 467 let upProgressCallback1 = (uploadedSize: number, totalSize: number) => { 468 console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); 469 }; 470 let upProgressCallback2 = (uploadedSize: number, totalSize: number) => { 471 console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); 472 }; 473 uploadTask.on('progress', upProgressCallback1); 474 uploadTask.on('progress', upProgressCallback2); 475 // Unsubscribe from upProgressCallback1. 476 uploadTask.off('progress', upProgressCallback1); 477 // Unsubscribe from all callbacks of upload progress events. 478 uploadTask.off('progress'); 479 ``` 480 481 482### off('headerReceive')<sup>7+</sup> 483 484off(type: 'headerReceive', callback?: (header: object) => void): void 485 486Unsubscribes from HTTP response events for the upload task. 487 488**System capability**: SystemCapability.MiscServices.Upload 489 490**Parameters** 491 492| Name| Type| Mandatory| Description| 493| -------- | -------- | -------- | -------- | 494| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response received).| 495| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 496 497**Error codes** 498 499For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 500 501| ID| Error Message| 502| -------- | -------- | 503| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 504 505**Example** 506 507<!--code_no_check--> 508 ```ts 509 let headerCallback1 = (header: object) => { 510 console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); 511 }; 512 let headerCallback2 = (header: object) => { 513 console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); 514 }; 515 uploadTask.on('headerReceive', headerCallback1); 516 uploadTask.on('headerReceive', headerCallback2); 517 // Unsubscribe from headerCallback1. 518 uploadTask.off('headerReceive', headerCallback1); 519 // Unsubscribe from all callbacks of the HTTP header events for the upload task. 520 uploadTask.off('headerReceive'); 521 ``` 522 523### off('complete' | 'fail')<sup>9+</sup> 524 525 off(type:'complete' | 'fail', callback?: Callback<Array<TaskState>>): void; 526 527Unsubscribes from upload completion or failure events. 528 529**System capability**: SystemCapability.MiscServices.Upload 530 531**Parameters** 532 533| Name| Type| Mandatory| Description| 534| -------- | -------- | -------- | -------- | 535| 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.| 536| callback | Callback<Array<TaskState>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 537 538**Error codes** 539 540For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 541 542| ID| Error Message| 543| -------- | -------- | 544| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 545 546**Example** 547 548<!--code_no_check--> 549 ```ts 550 let upCompleteCallback1 = (taskStates: Array<request.TaskState>) => { 551 console.info('Upload delete complete notification.'); 552 for (let i = 0; i < taskStates.length; i++) { 553 console.info('taskState:' + JSON.stringify(taskStates[i])); 554 } 555 }; 556 let upCompleteCallback2 = (taskStates: Array<request.TaskState>) => { 557 console.info('Upload delete complete notification.'); 558 for (let i = 0; i < taskStates.length; i++) { 559 console.info('taskState:' + JSON.stringify(taskStates[i])); 560 } 561 }; 562 uploadTask.on('complete', upCompleteCallback1); 563 uploadTask.on('complete', upCompleteCallback2); 564 // Unsubscribe from headerCallback1. 565 uploadTask.off('complete', upCompleteCallback1); 566 // Unsubscribe from all callbacks of the upload completion events. 567 uploadTask.off('complete'); 568 569 let upFailCallback1 = (taskStates: Array<request.TaskState>) => { 570 console.info('Upload delete fail notification.'); 571 for (let i = 0; i < taskStates.length; i++) { 572 console.info('taskState:' + JSON.stringify(taskStates[i])); 573 } 574 }; 575 let upFailCallback2 = (taskStates: Array<request.TaskState>) => { 576 console.info('Upload delete fail notification.'); 577 for (let i = 0; i < taskStates.length; i++) { 578 console.info('taskState:' + JSON.stringify(taskStates[i])); 579 } 580 }; 581 uploadTask.on('fail', upFailCallback1); 582 uploadTask.on('fail', upFailCallback2); 583 // Unsubscribe from headerCallback1. 584 uploadTask.off('fail', upFailCallback1); 585 // Unsubscribe from all callbacks of the upload failure events. 586 uploadTask.off('fail'); 587 ``` 588 589### delete<sup>9+</sup> 590delete(): Promise<boolean> 591 592Deletes this upload task. This API uses a promise to return the result. 593 594**Required permissions**: ohos.permission.INTERNET 595 596**System capability**: SystemCapability.MiscServices.Upload 597 598**Return value** 599 600| Type| Description| 601| -------- | -------- | 602| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 603 604**Error codes** 605 606For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 607 608| ID| Error Message| 609| -------- | -------- | 610| 201 | the permissions check fails | 611 612**Example** 613 614<!--code_no_check--> 615 ```ts 616 uploadTask.delete().then((result: boolean) => { 617 console.info('Succeeded in deleting the upload task.'); 618 }).catch((err: BusinessError) => { 619 console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); 620 }); 621 ``` 622 623> **NOTE** 624> 625> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 626 627 628### delete<sup>9+</sup> 629 630delete(callback: AsyncCallback<boolean>): void 631 632Deletes this upload task. This API uses an asynchronous callback to return the result. 633 634**Required permissions**: ohos.permission.INTERNET 635 636**System capability**: SystemCapability.MiscServices.Upload 637 638**Parameters** 639 640| Name| Type| Mandatory| Description| 641| -------- | -------- | -------- | -------- | 642| 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.| 643 644**Error codes** 645 646For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 647 648| ID| Error Message| 649| -------- | -------- | 650| 201 | the permissions check fails | 651 652**Example** 653 654<!--code_no_check--> 655 ```ts 656 uploadTask.delete((err: BusinessError, result: boolean) => { 657 if (err) { 658 console.error(`Failed to delete the upload task. Code: ${err.code}, message: ${err.message}`); 659 return; 660 } 661 console.info('Succeeded in deleting the upload task.'); 662 }); 663 ``` 664 665> **NOTE** 666> 667> The scenarios for triggering error code 401 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 668 669 670### remove<sup>(deprecated)</sup> 671 672remove(): Promise<boolean> 673 674Removes this upload task. This API uses a promise to return the result. 675 676> **NOTE** 677> 678> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9) instead. 679 680**Required permissions**: ohos.permission.INTERNET 681 682**System capability**: SystemCapability.MiscServices.Upload 683 684**Return value** 685 686| Type| Description| 687| -------- | -------- | 688| Promise<boolean> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| 689 690**Error codes** 691 692For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 693 694| ID| Error Message| 695| -------- | -------- | 696| 201 | the permissions check fails | 697 698**Example** 699 700 ```js 701 uploadTask.remove().then((result) => { 702 console.info('Succeeded in removing the upload task.'); 703 }).catch((err) => { 704 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 705 }); 706 ``` 707 708 709### remove<sup>(deprecated)</sup> 710 711remove(callback: AsyncCallback<boolean>): void 712 713Removes this upload task. This API uses an asynchronous callback to return the result. 714 715> **NOTE** 716> 717> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-1) instead. 718 719**Required permissions**: ohos.permission.INTERNET 720 721**System capability**: SystemCapability.MiscServices.Upload 722 723**Parameters** 724 725| Name| Type| Mandatory| Description| 726| -------- | -------- | -------- | -------- | 727| 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.| 728 729**Error codes** 730 731For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 732 733| ID| Error Message| 734| -------- | -------- | 735| 201 | the permissions check fails | 736 737**Example** 738 739 ```js 740 uploadTask.remove((err, result) => { 741 if (err) { 742 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 743 return; 744 } 745 if (result) { 746 console.info('Succeeded in removing the upload task.'); 747 } else { 748 console.error(`Failed to remove the upload task. Code: ${err.code}, message: ${err.message}`); 749 } 750 }); 751 ``` 752 753## UploadConfig<sup>6+</sup> 754Describes the configuration of an upload task. 755 756**System capability**: SystemCapability.MiscServices.Upload 757 758| Name| Type| Mandatory| Description| 759| -------- | -------- | -------- | -------- | 760| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.| 761| header | Object | Yes| HTTP or HTTPS header added to an upload request.| 762| 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.| 763| index<sup>11+</sup> | number | No| Path index of the task. The default value is **0**.| 764| 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.| 765| 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.| 766| files | Array<[File](#file)> | Yes| List of files to upload. The files are submitted in multipart/form-data format.| 767| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| 768 769## TaskState<sup>9+</sup> 770Implements 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. 771 772**System capability**: SystemCapability.MiscServices.Upload 773 774| Name| Type| Mandatory| Description | 775| -------- | -------- | -------- |-------------------------------------------------------------------------------------------------------------------------------------------| 776| path | string | Yes| File path. | 777| 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.| 778| message | string | Yes| Description of the upload task result. | 779 780The following table describes the enum values of **responseCode**. 781 782| Result Code| Description | 783|-----|------------------------------------| 784| 0 | Upload success. | 785| 5 | Task suspended or stopped proactively. | 786| 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. | 787| 7 | No network connection. Check whether the device is connected to the network. | 788| 8 | Network mismatch. Check whether the current network type matches the network type required by the task. | 789| 10 | Failed to create the HTTP request. Verify the parameters or try again. | 790| 12 | Request timeout. Verify the parameter configuration or the network connection, or try again. | 791| 13 | Connection failed. Verify the parameter configuration or the network connection, or try again. | 792| 14 | Request failed. Verify the parameter configuration or the network connection, or try again. | 793| 15 | Upload failed. Verify the parameter configuration or the network connection, or try again. | 794| 16 | Redirection failed. Verify the parameter configuration or the network connection, or try again. | 795| 17 | Protocol error. The server returns a 4XX or 5XX status code. Verify the parameter configuration and try again.| 796| 20 | Other errors. Verify the parameter configuration or the network connection, or try again. | 797 798## File 799Defines the file list in [UploadConfig<sup>6+<sup>](#uploadconfig6). 800 801**System capability**: SystemCapability.MiscServices.Download 802 803| Name| Type| Mandatory| Description| 804| -------- | -------- | -------- | -------- | 805| filename | string | Yes| File name in the header when **multipart** is used.| 806| name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| 807| 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>Example: **internal://cache/path/to/file.txt** | 808| type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| 809 810 811## RequestData 812Defines the form data in [UploadConfig<sup>6+<sup>](#uploadconfig6). 813 814**System capability**: SystemCapability.MiscServices.Download 815 816| Name| Type| Mandatory| Description| 817| -------- | -------- | -------- | -------- | 818| name | string | Yes| Name of a form element.| 819| value | string | Yes| Value of a form element.| 820 821## request.downloadFile<sup>9+</sup> 822 823downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> 824 825Downloads files. This API uses a promise to return the result. 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. 826 827**Required permissions**: ohos.permission.INTERNET 828 829**System capability**: SystemCapability.MiscServices.Download 830 831**Parameters** 832 833| Name| Type| Mandatory| Description| 834| -------- | -------- | -------- | -------- | 835| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 836| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 837 838**Return value** 839 840| Type| Description| 841| -------- | -------- | 842| Promise<[DownloadTask](#downloadtask)> | Promise used to return the download task.| 843 844**Error codes** 845 846For details about the following error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 847 848| ID| Error Message| 849| -------- | -------- | 850| 201 | the permissions check fails | 851| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 852| 13400001 | file operation error. | 853| 13400002 | bad file path. | 854| 13400003 | task service ability error. | 855 856**Example** 857 858 ```ts 859import { BusinessError } from '@kit.BasicServicesKit'; 860 861 try { 862 // Replace the URL with the HTTP address of the real server. 863 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 864 let downloadTask: request.DownloadTask = data; 865 }).catch((err: BusinessError) => { 866 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 867 }) 868 } catch (err) { 869 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 870 } 871 ``` 872 873> **NOTE** 874> 875> 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). 876 877 878## request.downloadFile<sup>9+</sup> 879 880downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; 881 882Downloads files. This API uses an asynchronous callback to return the result. 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. 883 884**Required permissions**: ohos.permission.INTERNET 885 886**System capability**: SystemCapability.MiscServices.Download 887 888**Parameters** 889 890| Name| Type| Mandatory| Description| 891| -------- | -------- | -------- | -------- | 892| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 893| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 894| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the download task.| 895 896**Error codes** 897 898For details about the following error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 899 900| ID| Error Message| 901| -------- | -------- | 902| 201 | the permissions check fails | 903| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 904| 13400001 | file operation error. | 905| 13400002 | bad file path. | 906| 13400003 | task service ability error. | 907 908**Example** 909 910 ```ts 911import { BusinessError } from '@kit.BasicServicesKit'; 912 913 try { 914 // Replace the URL with the HTTP address of the real server. 915 request.downloadFile(getContext(), { 916 url: 'https://xxxx/xxxxx.hap', 917 filePath: 'xxx/xxxxx.hap' 918 }, (err: BusinessError, data: request.DownloadTask) => { 919 if (err) { 920 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 921 return; 922 } 923 let downloadTask: request.DownloadTask = data; 924 }); 925 } catch (err) { 926 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 927 } 928 ``` 929 930> **NOTE** 931> 932> 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). 933 934## request.download<sup>(deprecated)</sup> 935 936download(config: DownloadConfig): Promise<DownloadTask> 937 938Downloads files. This API uses a promise to return the result. 939 940> **NOTE** 941> 942> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9) instead. 943 944**Model restriction**: This API can be used only in the FA model. 945 946**Required permissions**: ohos.permission.INTERNET 947 948**System capability**: SystemCapability.MiscServices.Download 949 950**Parameters** 951 952| Name| Type| Mandatory| Description| 953| -------- | -------- | -------- | -------- | 954| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 955 956**Return value** 957 958| Type| Description| 959| -------- | -------- | 960| Promise<[DownloadTask](#downloadtask)> | Promise used to return the download task.| 961 962**Error codes** 963 964For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 965 966| ID| Error Message| 967| -------- | -------- | 968| 201 | the permissions check fails | 969 970**Example** 971 972 ```js 973 let downloadTask; 974 // Replace the URL with the HTTP address of the real server. 975 request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { 976 downloadTask = data; 977 }).catch((err) => { 978 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 979 }) 980 ``` 981 982 983## request.download<sup>(deprecated)</sup> 984 985download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void 986 987Downloads files. This API uses an asynchronous callback to return the result. 988 989> **NOTE** 990> 991> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1) instead. 992 993**Model restriction**: This API can be used only in the FA model. 994 995**Required permissions**: ohos.permission.INTERNET 996 997**System capability**: SystemCapability.MiscServices.Download 998 999**Parameters** 1000 1001| Name| Type| Mandatory| Description| 1002| -------- | -------- | -------- | -------- | 1003| config | [DownloadConfig](#downloadconfig) | Yes| Download configuration.| 1004| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the download task.| 1005 1006**Error codes** 1007 1008For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 1009 1010| ID| Error Message| 1011| -------- | -------- | 1012| 201 | the permissions check fails | 1013 1014**Example** 1015 1016 ```js 1017 let downloadTask; 1018 // Replace the URL with the HTTP address of the real server. 1019 request.download({ url: 'https://xxxx/xxxxx.hap', 1020 filePath: 'xxx/xxxxx.hap'}, (err, data) => { 1021 if (err) { 1022 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1023 return; 1024 } 1025 downloadTask = data; 1026 }); 1027 ``` 1028 1029## DownloadTask 1030 1031Implements 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. 1032 1033 1034### on('progress') 1035 1036on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void 1037 1038Subscribes to download progress events. This API uses a callback to return the result asynchronously. 1039 1040> **NOTE** 1041> 1042> To maintain a balance between power consumption and performance, this API cannot be called when the application is running in the background. 1043 1044**System capability**: SystemCapability.MiscServices.Download 1045 1046**Parameters** 1047 1048| Name| Type| Mandatory| Description| 1049| -------- | -------- | -------- | -------- | 1050| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| 1051| callback | function | Yes| Callback used to return the result.| 1052 1053 Parameters of the callback function 1054 1055| Name| Type| Mandatory| Description | 1056| -------- | -------- | -------- |-------------------------------------------------------------------------| 1057| receivedSize | number | Yes| Size of the downloaded files, in bytes. | 1058| 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**.| 1059 1060**Error codes** 1061 1062For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1063 1064| ID| Error Message| 1065| -------- | -------- | 1066| 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 1067 1068**Example** 1069 1070 ```ts 1071import { BusinessError } from '@kit.BasicServicesKit'; 1072 1073 try { 1074 // Replace the URL with the HTTP address of the real server. 1075 request.downloadFile(getContext(), { url: 'https://xxxx/xxxx.hap' }).then((data: request.DownloadTask) => { 1076 let downloadTask: request.DownloadTask = data; 1077 let progressCallback = (receivedSize: number, totalSize: number) => { 1078 console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); 1079 }; 1080 downloadTask.on('progress', progressCallback); 1081 }).catch((err: BusinessError) => { 1082 console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 1083 }) 1084 } catch (err) { 1085 console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 1086 } 1087 ``` 1088 1089 1090### off('progress') 1091 1092off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void 1093 1094Unsubscribes from download progress events. 1095 1096**System capability**: SystemCapability.MiscServices.Download 1097 1098**Parameters** 1099 1100| Name| Type| Mandatory| Description| 1101| -------- | -------- | -------- | -------- | 1102| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| 1103| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.<br>**receivedSize**: size of the downloaded files.<br>**totalSize**: total size of the files to download.| 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 a callback to return the result asynchronously. 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](#download-error-codes).| 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 do not actually exist. Therefore, `401 the parameters check fails` 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 do not actually exist. Therefore, `401 the parameters check fails` 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 download task information.| 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 do not actually exist. Therefore, `401 the parameters check fails` 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 download task information.| 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 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1587 1588 1589### getTaskMimeType<sup>9+</sup> 1590 1591getTaskMimeType(): Promise<string> 1592 1593Queries **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** of the download task.| 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 do not actually exist. Therefore, `401 the parameters check fails` 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 **MimeType** of the download task.| 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 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1691 1692 1693### suspend<sup>9+</sup> 1694 1695suspend(): Promise<boolean> 1696 1697Pauses 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.| 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 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1742 1743 1744### suspend<sup>9+</sup> 1745 1746suspend(callback: AsyncCallback<boolean>): void 1747 1748Pauses 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.| 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 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1795 1796 1797### restore<sup>9+</sup> 1798 1799restore(): Promise<boolean> 1800 1801Resumes 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.| 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 do not actually exist. Therefore, `401 the parameters check fails` is removed from API version 12. 1846 1847 1848### restore<sup>9+</sup> 1849 1850restore(callback: AsyncCallback<boolean>): void 1851 1852Resumes 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.| 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 do not actually exist. Therefore, `401 the parameters check fails` 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.| 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.| 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 download task information.| 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 download task information.| 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** of the download task.| 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 **MimeType** of the download task.| 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 used to return the result.| 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.| 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 used to return the result.| 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.| 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. The value contains a maximum of 2048 characters.| 2309| header | Object | No| HTTPS flag header to be included in the download request.| 2310| enableMetered | boolean | No| Whether download is allowed on a metered connection. The default value is **false**. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.<br>- **true**: allowed<br>- **false**: not allowed| 2311| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.<br>- **true**: allowed<br>- **false**: not allowed| 2312| description | string | No| Description of the download session.| 2313| filePath<sup>7+</sup> | string | No| Path where the downloaded file is stored. The default value is the cache directory of the caller (that is, the input **context**). The default file name is the part truncated from the last slash (/) in the URL.<br>- In the FA model, use [context](../apis-ability-kit/js-apis-inner-app-context.md#contextgetcachedir) to obtain the application storage path.<br>- In the stage model, use [AbilityContext](../apis-ability-kit/js-apis-inner-application-context.md) to obtain the application storage path.| 2314| networkType | number | No| Network type allowed for the download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.<br>- NETWORK_MOBILE: 0x00000001<br>- NETWORK_WIFI: 0x00010000| 2315| title | string | No| Download task name.| 2316| background<sup>9+</sup> | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| 2317 2318 2319## DownloadInfo<sup>7+</sup> 2320Defines the download task information, which is the callback parameter of the [getTaskInfo<sup>9+</sup>](#gettaskinfo9) API. 2321 2322**System capability**: SystemCapability.MiscServices.Download 2323 2324| Name| Type|Mandatory| Description| 2325| -------- | -------- | -------- | -------- | 2326| downloadId | number |Yes| ID of the download task.| 2327| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| 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](#causes-of-download-pause).| 2331| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| 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| Size of the files downloaded, 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 2385You can use the **CommonEventData** type to transmit data related to common events. The members in **CommonEventData** are different from those described in [CommonEventData](js-apis-inner-commonEvent-commonEventData.md). Specifically, **CommonEventData.code** indicates the task status, which is **0x40 COMPLETE** or **0x41 FAILED**, and **CommonEventData.data** indicates the task ID. 2386 2387<!--Del--> 2388For details about event configuration information, see [Subscribing to Common Events in Static Mode (for System Applications Only)](../../basic-services/common-event/common-event-static-subscription.md).<!--DelEnd--> 2389 2390**System capability**: SystemCapability.Request.FileTransferAgent 2391 2392| Name| Value| Description | 2393| -------- | ------- |-----------| 2394| COMPLETE | 'ohos.request.event.COMPLETE' | Task completion event.| 2395 2396## FileSpec<sup>10+</sup> 2397Provides the file information of a table item. 2398 2399**Atomic service API**: This API can be used in atomic services since API version 11. 2400 2401**System capability**: SystemCapability.Request.FileTransferAgent 2402 2403| Name| Type| Mandatory| Description| 2404| -------- | -------- | -------- | -------- | 2405| path | string | Yes| File path:<br>- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.<br>- Internal protocol path, which can be **internal://** or its subdirectory. **internal** indicates the cache directory of the caller (that is, the input **context**), and **internal://cache** corresponds to **context.cacheDir**, for example, **internal://cache/path/to/file.txt**.<br>- Application sandbox directory. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.<br>- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>- User public file, for example, **file://media/Photo/path/to/file.img**. Only frontend tasks are supported.| 2406| mimeType | string | No| MIME type of the file, which is obtained from the file name.| 2407| filename | string | No| File name. The default value is obtained from the file path.| 2408| extras | object | No| Additional information of the file.| 2409 2410 2411## FormItem<sup>10+</sup> 2412Describes the form item of a task. 2413 2414**Atomic service API**: This API can be used in atomic services since API version 11. 2415 2416**System capability**: SystemCapability.Request.FileTransferAgent 2417 2418| Name| Type| Mandatory| Description| 2419| -------- | -------- | -------- | -------- | 2420| name | string | Yes| Form parameter name.| 2421| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes| Form parameter value.| 2422 2423 2424## Config<sup>10+</sup> 2425Provides the configuration information of an upload or download task. 2426 2427**System capability**: SystemCapability.Request.FileTransferAgent 2428 2429| Name| Type| Mandatory| Description| 2430| -------- | -------- | -------- | -------- | 2431| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2432| url | string | Yes| Resource URL. The value contains a maximum of 2048 characters.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2433| title | string | No| Task title. The value contains a maximum of 256 characters. The default value is **upload** or **download** in lowercase. Set the value to that of **action**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2434| description | string | No| Task description. The value contains a maximum of 1024 characters. The default value is a null string.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2435| mode | [Mode](#mode10) | No| Task mode. The default mode is background.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2436| overwrite | boolean | No| Whether to overwrite an existing file during the download. The default value is **false**.<br>- **true**: Overwrite the existing file.<br>- **false**: Do not overwrite the existing file. In this case, the download fails.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2437| method | string | No| Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.<br>- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.<br>- If the task is a download, use **GET** or **POST**. The default value is **GET**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2438| headers | object | No| HTTP headers to be included in the task.<br>- If the task is an upload, the default **Content-Type** is **multipart/form-data**.<br>- If the task is a download, the default **Content-Type** is **application/json**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2439| data | string \| Array<[FormItem](#formitem10)> | No| Task data.<br>- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.<br>- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2440| saveas | string | No| Path for storing downloaded files. The options are as follows:<br>- Relative path, which is in the cache directory of the caller, for example, **./xxx/yyy/zzz.html** or **xxx/yyy/zzz.html**.<br>- Internal protocol path, which can be **internal://** or its subdirectory. **internal** indicates the cache directory of the caller (that is, the input **context**), and **internal://cache** corresponds to **context.cacheDir**. for example, **internal://cache/path/to/file.txt**.<br>- Application sandbox directory. Only the **base** directory and its subdirectories are supported, for example, **/data/storage/el1/base/path/to/file.txt**.<br>- File protocol path, which must match the application bundle name. Only the **base** directory and its subdirectories are supported, for example, **file://com.example.test/data/storage/el2/base/file.txt**.<br>The default value is the cache directory of the caller (that is, the input **context**). The default file name is the part truncated from the last slash (/) in the URL.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2441| network | [Network](#network10) | No| Network used for the task. The default value is **ANY** (Wi-Fi or cellular).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2442| metered | boolean | No| Whether the task is allowed on a metered connection. The default value is **false**.<br>- **true**: task allowed on a metered connection.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2443| roaming | boolean | No| Whether the task is allowed on a roaming network. The default value is **true**.<br>- **true**: task allowed on a roaming network.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2444| retry | boolean | No| Whether automatic retry is enabled for the task. This parameter is only applicable to background tasks. The default value is **true**.<br>- **true**: automatic retry enabled for the task.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2445| redirect | boolean | No| Whether redirection is allowed. The default value is **true**.<br>- **true**: redirection allowed.<br>- **false**: task not allowed on a metered connection.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2446| proxy<sup>12+</sup> | string | No| Proxy address. The value contains a maximum of 512 characters.<br>It is in the format of http://\<domain or address\>:\<port\>. By default, this parameter is left blank.| 2447| index | number | No| Path index of the task. It is usually used for resumable downloads. The default value is **0**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2448| begins | number | No| File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the beginning of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2449| ends | number | No| File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.<br>- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.<br>- If the task is an upload, the value is obtained at the end of the upload.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2450| gauge | boolean | No| Whether to send progress notifications. This parameter applies only to background tasks. The default value is **false**.<br>- **false**: Progress notifications are not sent. This means that a notification is sent only to indicate the result of the total task.<br>- **true**: Progress notifications are sent to indicate the result of each file.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2451| precise | boolean | No| - If this parameter is set to **true**, the task fails when the file size cannot be obtained.<br>- If this parameter is set to **false**, the task continues when the file size is set to **-1**.<br>The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2452| token | string | No| Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2453| priority<sup>11+</sup> | number | No| Priority of the task. For tasks in the same mode, a smaller value indicates a higher priority.<br>Default value: **0**| 2454| extras | object | No| Additional information of the task. This parameter is left empty by default.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 2455 2456## State<sup>10+</sup> 2457 2458Defines the current task status. 2459 2460**Atomic service API**: This API can be used in atomic services since API version 11. 2461 2462**System capability**: SystemCapability.Request.FileTransferAgent 2463 2464| Name| Value|Description| 2465| -------- | -------- |-------- | 2466| INITIALIZED | 0x00 |The task is initialized based on the configuration specified in [Config](#config10).| 2467| WAITING | 0x10 |The task lacks resources for running or the resources for retries do not match the network status.| 2468| RUNNING | 0x20 |The task is being executed.| 2469| RETRYING | 0x21 |The task has failed at least once and is being executed again.| 2470| PAUSED | 0x30 |The task is suspended and will be resumed later.| 2471| STOPPED | 0x31 |The task is stopped.| 2472| COMPLETED | 0x40 |The task is complete.| 2473| FAILED | 0x41 |The task fails.| 2474| REMOVED | 0x50 |The task is removed.| 2475 2476 2477## Progress<sup>10+</sup> 2478Describes the data structure of the task progress. 2479 2480**Atomic service API**: This API can be used in atomic services since API version 11. 2481 2482**System capability**: SystemCapability.Request.FileTransferAgent 2483 2484| Name| Type| Mandatory| Description | 2485| -------- | -------- | -------- |---------------------------------------------------------------------| 2486| state | [State](#state10) | Yes| Current task status. | 2487| index | number | Yes| Index of the file that is being processed in the task. | 2488| processed | number | Yes| Size of processed data in the current file in the task, in bytes. | 2489| sizes | Array<number> | Yes| Size of files in the 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**.| 2490| extras | object | No| Extra information of the task, for example, the header and body of the response from the server. | 2491 2492 2493## Faults<sup>10+</sup> 2494 2495Defines the cause of a task failure. 2496 2497**Atomic service API**: This API can be used in atomic services since API version 11. 2498 2499**System capability**: SystemCapability.Request.FileTransferAgent 2500 2501| Name| Value| Description | 2502| -------- | -------- |--------------------------------------------------------------------------------| 2503| OTHERS | 0xFF | Other fault. | 2504| DISCONNECTED | 0x00 | Network disconnection. | 2505| TIMEOUT | 0x10 | Timeout. | 2506| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | 2507| 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. | 2508| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | 2509| DNS<sup>12+</sup> | 0x50 | DNS resolution error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2510| TCP<sup>12+</sup> | 0x60 | TCP connection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2511| 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.| 2512| REDIRECT<sup>12+</sup> | 0x80 | Redirection error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 2513 2514> **NOTE** 2515> 2516> 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. 2517 2518## Filter<sup>10+</sup> 2519Defines the filter criteria. 2520 2521**System capability**: SystemCapability.Request.FileTransferAgent 2522 2523| Name| Type| Mandatory| Description| 2524| -------- | -------- | -------- | -------- | 2525| before | number | No| Unix timestamp of the end time, in milliseconds. The default value is the invoking time.| 2526| after | number | No| Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours.| 2527| state | [State](#state10) | No| Task state.| 2528| action | [Action](#action10) | No| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2529| mode | [Mode](#mode10) | No| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.<br>- No value: All tasks are queried.| 2530 2531## TaskInfo<sup>10+</sup> 2532Defines the data structure of the task information for query. The fields available vary depending on the query type. 2533 2534**System capability**: SystemCapability.Request.FileTransferAgent 2535 2536| Name| Type| Mandatory| Description| 2537| -------- | -------- | -------- | -------- | 2538| saveas | string | No| Path for storing downloaded files.| 2539| 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).| 2540| 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).| 2541| tid | string | Yes| Task ID.| 2542| title | string | Yes| Task title.| 2543| description | string | Yes| Task description.| 2544| action | [Action](#action10) | Yes| Task action.<br>- **UPLOAD**<br>- **DOWNLOAD**| 2545| mode | [Mode](#mode10) | Yes| Task mode.<br>- **FOREGROUND**: foreground task.<br>- **BACKGROUND**: background task.| 2546| 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.| 2547| mimeType | string | Yes| MIME type in the task configuration.| 2548| progress | [Progress](#progress10) | Yes| Task progress.| 2549| gauge | boolean | Yes| Whether to send progress notifications. This parameter applies only to background tasks.| 2550| 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). | 2551| mtime | number | Yes | Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device. | 2552| retry | boolean | Yes | Whether automatic retry is enabled for the task. This parameter applies only to background tasks. | 2553| tries | number | Yes | Number of retries of the task. | 2554| faults | [Faults](#faults10) | Yes | Failure cause of the task. | 2555| reason | string | Yes | Reason why the task is waiting, failed, stopped, or paused. | 2556| extras | object | No | Extra information of the task. | 2557 2558## HttpResponse<sup>12+</sup> 2559Data structure of the task response header. 2560 2561**Atomic service API**: This API can be used in atomic services since API version 12. 2562 2563**System capability**: SystemCapability.Request.FileTransferAgent 2564 2565| Name| Type| Mandatory| Description| 2566| -------- | -------- | -------- | -------- | 2567| version | string | Yes| HTTP version.| 2568| statusCode | number | Yes| HTTP response status code.| 2569| reason | string | Yes| HTTP response cause.| 2570| headers | Map<string, Array<string>> | Yes| HTTP response header.| 2571 2572## Task<sup>10+</sup> 2573Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create<sup>10+</sup>](#requestagentcreate10-1) or from a callback through [request.agent.create<sup>10+</sup>](#requestagentcreate10). 2574 2575### Attributes 2576Task attributes include the task ID and task configuration. 2577 2578**Atomic service API**: This API can be used in atomic services since API version 11. 2579 2580**System capability**: SystemCapability.Request.FileTransferAgent 2581 2582| Name| Type| Mandatory| Description| 2583| -------- | -------- | -------- | -------- | 2584| tid | string | Yes| Task ID, which is unique in the system and is automatically generated by the system.| 2585| config | [Config](#config10) | Yes| Task configuration.| 2586 2587 2588### on('progress')<sup>10+</sup> 2589 2590on(event: 'progress', callback: (progress: Progress) => void): void 2591 2592Subscribes to task progress changes. This API uses a callback to return the result asynchronously. 2593 2594**Atomic service API**: This API can be used in atomic services since API version 11. 2595 2596**System capability**: SystemCapability.Request.FileTransferAgent 2597 2598**Parameters** 2599 2600| Name| Type| Mandatory| Description| 2601| -------- | -------- | -------- | -------- | 2602| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 2603| callback | function | Yes| Callback used to return the data structure of the task progress.| 2604 2605**Error codes** 2606 2607For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2608 2609| ID| Error Message| 2610| -------- | -------- | 2611| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2612 2613**Example** 2614 2615 ```ts 2616 import { BusinessError } from '@kit.BasicServicesKit'; 2617 2618 let attachments: Array<request.agent.FormItem> = [{ 2619 name: "taskOnTest", 2620 value: { 2621 filename: "taskOnTest.avi", 2622 mimeType: "application/octet-stream", 2623 path: "./taskOnTest.avi", 2624 } 2625 }]; 2626 let config: request.agent.Config = { 2627 action: request.agent.Action.UPLOAD, 2628 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2629 title: 'taskOnTest', 2630 description: 'Sample code for event listening', 2631 mode: request.agent.Mode.FOREGROUND, 2632 overwrite: false, 2633 method: "PUT", 2634 data: attachments, 2635 saveas: "./", 2636 network: request.agent.Network.CELLULAR, 2637 metered: false, 2638 roaming: true, 2639 retry: true, 2640 redirect: true, 2641 index: 0, 2642 begins: 0, 2643 ends: -1, 2644 gauge: false, 2645 precise: false, 2646 token: "it is a secret" 2647 }; 2648 let createOnCallback = (progress: request.agent.Progress) => { 2649 console.info('upload task progress.'); 2650 }; 2651 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2652 task.on('progress', createOnCallback); 2653 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2654 task.start(); 2655 }).catch((err: BusinessError) => { 2656 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2657 }); 2658 ``` 2659 2660> **NOTE** 2661> 2662> 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). 2663 2664### on('completed')<sup>10+</sup> 2665 2666on(event: 'completed', callback: (progress: Progress) => void): void 2667 2668Subscribes to task completion events. This API uses a callback to return the result asynchronously. 2669 2670**Atomic service API**: This API can be used in atomic services since API version 11. 2671 2672**System capability**: SystemCapability.Request.FileTransferAgent 2673 2674**Parameters** 2675 2676| Name| Type| Mandatory| Description| 2677| -------- | -------- | -------- | -------- | 2678| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 2679| callback | function | Yes| Callback used to return the data structure of the task progress.| 2680 2681**Error codes** 2682 2683For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2684 2685| ID| Error Message| 2686| -------- | -------- | 2687| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2688 2689**Example** 2690 2691 ```ts 2692 import { BusinessError } from '@kit.BasicServicesKit'; 2693 2694 let attachments: Array<request.agent.FormItem> = [{ 2695 name: "taskOnTest", 2696 value: { 2697 filename: "taskOnTest.avi", 2698 mimeType: "application/octet-stream", 2699 path: "./taskOnTest.avi", 2700 } 2701 }]; 2702 let config: request.agent.Config = { 2703 action: request.agent.Action.UPLOAD, 2704 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2705 title: 'taskOnTest', 2706 description: 'Sample code for event listening', 2707 mode: request.agent.Mode.FOREGROUND, 2708 overwrite: false, 2709 method: "PUT", 2710 data: attachments, 2711 saveas: "./", 2712 network: request.agent.Network.CELLULAR, 2713 metered: false, 2714 roaming: true, 2715 retry: true, 2716 redirect: true, 2717 index: 0, 2718 begins: 0, 2719 ends: -1, 2720 gauge: false, 2721 precise: false, 2722 token: "it is a secret" 2723 }; 2724 let createOnCallback = (progress: request.agent.Progress) => { 2725 console.info('upload task completed.'); 2726 }; 2727 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2728 task.on('completed', createOnCallback); 2729 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2730 task.start(); 2731 }).catch((err: BusinessError) => { 2732 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2733 }); 2734 ``` 2735 2736> **NOTE** 2737> 2738> 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). 2739 2740### on('failed')<sup>10+</sup> 2741 2742on(event: 'failed', callback: (progress: Progress) => void): void 2743 2744Subscribes to task failure events. This API uses a callback to return the result asynchronously. 2745 2746**Atomic service API**: This API can be used in atomic services since API version 11. 2747 2748**System capability**: SystemCapability.Request.FileTransferAgent 2749 2750**Parameters** 2751 2752| Name| Type| Mandatory| Description| 2753| -------- | -------- | -------- | -------- | 2754| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 2755| callback | function | Yes| Callback used to return the data structure of the task progress.| 2756 2757**Error codes** 2758 2759For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 2760 2761| ID| Error Message| 2762| -------- | -------- | 2763| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2764 2765**Example** 2766 2767 ```ts 2768 import { BusinessError } from '@kit.BasicServicesKit'; 2769 2770 let attachments: Array<request.agent.FormItem> = [{ 2771 name: "taskOnTest", 2772 value: { 2773 filename: "taskOnTest.avi", 2774 mimeType: "application/octet-stream", 2775 path: "./taskOnTest.avi", 2776 } 2777 }]; 2778 let config: request.agent.Config = { 2779 action: request.agent.Action.UPLOAD, 2780 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2781 title: 'taskOnTest', 2782 description: 'Sample code for event listening', 2783 mode: request.agent.Mode.FOREGROUND, 2784 overwrite: false, 2785 method: "PUT", 2786 data: attachments, 2787 saveas: "./", 2788 network: request.agent.Network.CELLULAR, 2789 metered: false, 2790 roaming: true, 2791 retry: true, 2792 redirect: true, 2793 index: 0, 2794 begins: 0, 2795 ends: -1, 2796 gauge: false, 2797 precise: false, 2798 token: "it is a secret" 2799 }; 2800 let createOnCallback = (progress: request.agent.Progress) => { 2801 console.info('upload task failed.'); 2802 }; 2803 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2804 task.on('failed', createOnCallback); 2805 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2806 task.start(); 2807 }).catch((err: BusinessError) => { 2808 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2809 }); 2810 ``` 2811 2812> **NOTE** 2813> 2814> 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). 2815 2816### on('pause')<sup>11+</sup> 2817 2818on(event: 'pause', callback: (progress: Progress) => void): void 2819 2820Subscribes to task pause events. This API uses a callback to return the result asynchronously. 2821 2822**System capability**: SystemCapability.Request.FileTransferAgent 2823 2824**Parameters** 2825 2826| Name| Type| Mandatory| Description| 2827| -------- | -------- | -------- | -------- | 2828| event | string | Yes| Type of the event to subscribe to.<br>The value is **'pause'**, indicating task pause.| 2829| callback | function | Yes| Callback used to return the data structure of the task progress.| 2830 2831**Error codes** 2832 2833For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2834 2835| ID| Error Message| 2836| -------- | -------- | 2837| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2838 2839**Example** 2840 2841 ```ts 2842 import { BusinessError } from '@kit.BasicServicesKit'; 2843 2844 let attachments: Array<request.agent.FormItem> = [{ 2845 name: "taskOnTest", 2846 value: { 2847 filename: "taskOnTest.avi", 2848 mimeType: "application/octet-stream", 2849 path: "./taskOnTest.avi", 2850 } 2851 }]; 2852 let config: request.agent.Config = { 2853 action: request.agent.Action.UPLOAD, 2854 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2855 title: 'taskOnTest', 2856 description: 'Sample code for event listening', 2857 mode: request.agent.Mode.FOREGROUND, 2858 overwrite: false, 2859 method: "PUT", 2860 data: attachments, 2861 saveas: "./", 2862 network: request.agent.Network.CELLULAR, 2863 metered: false, 2864 roaming: true, 2865 retry: true, 2866 redirect: true, 2867 index: 0, 2868 begins: 0, 2869 ends: -1, 2870 gauge: false, 2871 precise: false, 2872 token: "it is a secret" 2873 }; 2874 let createOnCallback = (progress: request.agent.Progress) => { 2875 console.info('upload task pause.'); 2876 }; 2877 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2878 task.on('pause', createOnCallback); 2879 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2880 task.start(); 2881 }).catch((err: BusinessError) => { 2882 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2883 }); 2884 ``` 2885 2886> **NOTE** 2887> 2888> 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). 2889 2890### on('resume')<sup>11+</sup> 2891 2892on(event: 'resume', callback: (progress: Progress) => void): void 2893 2894Subscribes to task resume events. This API uses a callback to return the result asynchronously. 2895 2896**System capability**: SystemCapability.Request.FileTransferAgent 2897 2898**Parameters** 2899 2900| Name| Type| Mandatory| Description| 2901| -------- | -------- | -------- | -------- | 2902| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 2903| callback | function | Yes| Callback used to return the data structure of the task progress.| 2904 2905**Error codes** 2906 2907For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2908 2909| ID| Error Message| 2910| -------- | -------- | 2911| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2912 2913**Example** 2914 2915 ```ts 2916 import { BusinessError } from '@kit.BasicServicesKit'; 2917 2918 let attachments: Array<request.agent.FormItem> = [{ 2919 name: "taskOnTest", 2920 value: { 2921 filename: "taskOnTest.avi", 2922 mimeType: "application/octet-stream", 2923 path: "./taskOnTest.avi", 2924 } 2925 }]; 2926 let config: request.agent.Config = { 2927 action: request.agent.Action.UPLOAD, 2928 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 2929 title: 'taskOnTest', 2930 description: 'Sample code for event listening', 2931 mode: request.agent.Mode.FOREGROUND, 2932 overwrite: false, 2933 method: "PUT", 2934 data: attachments, 2935 saveas: "./", 2936 network: request.agent.Network.CELLULAR, 2937 metered: false, 2938 roaming: true, 2939 retry: true, 2940 redirect: true, 2941 index: 0, 2942 begins: 0, 2943 ends: -1, 2944 gauge: false, 2945 precise: false, 2946 token: "it is a secret" 2947 }; 2948 let createOnCallback = (progress: request.agent.Progress) => { 2949 console.info('upload task resume.'); 2950 }; 2951 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 2952 task.on('resume', createOnCallback); 2953 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 2954 task.start(); 2955 }).catch((err: BusinessError) => { 2956 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 2957 }); 2958 ``` 2959 2960> **NOTE** 2961> 2962> 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). 2963 2964### on('remove')<sup>11+</sup> 2965 2966on(event: 'remove', callback: (progress: Progress) => void): void 2967 2968Subscribes to task removal events. This API uses a callback to return the result asynchronously. 2969 2970**System capability**: SystemCapability.Request.FileTransferAgent 2971 2972**Parameters** 2973 2974| Name| Type| Mandatory| Description| 2975| -------- | -------- | -------- | -------- | 2976| event | string | Yes| Type of the event to subscribe to.<br>The value is **'remove'**, indicating task removal.| 2977| callback | function | Yes| Callback used to return the data structure of the task progress.| 2978 2979**Error codes** 2980 2981For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2982 2983| ID| Error Message| 2984| -------- | -------- | 2985| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 2986 2987**Example** 2988 2989 ```ts 2990 import { BusinessError } from '@kit.BasicServicesKit'; 2991 2992 let attachments: Array<request.agent.FormItem> = [{ 2993 name: "taskOnTest", 2994 value: { 2995 filename: "taskOnTest.avi", 2996 mimeType: "application/octet-stream", 2997 path: "./taskOnTest.avi", 2998 } 2999 }]; 3000 let config: request.agent.Config = { 3001 action: request.agent.Action.UPLOAD, 3002 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3003 title: 'taskOnTest', 3004 description: 'Sample code for event listening', 3005 mode: request.agent.Mode.FOREGROUND, 3006 overwrite: false, 3007 method: "PUT", 3008 data: attachments, 3009 saveas: "./", 3010 network: request.agent.Network.CELLULAR, 3011 metered: false, 3012 roaming: true, 3013 retry: true, 3014 redirect: true, 3015 index: 0, 3016 begins: 0, 3017 ends: -1, 3018 gauge: false, 3019 precise: false, 3020 token: "it is a secret" 3021 }; 3022 let createOnCallback = (progress: request.agent.Progress) => { 3023 console.info('upload task remove.'); 3024 }; 3025 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3026 task.on('remove', createOnCallback); 3027 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3028 task.start(); 3029 }).catch((err: BusinessError) => { 3030 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3031 }); 3032 ``` 3033 3034> **NOTE** 3035> 3036> 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). 3037 3038### on('response')<sup>12+</sup> 3039 3040on(event: 'response', callback: Callback<HttpResponse>): void 3041 3042Subscribes to task response headers. This API uses an asynchronous callback to return the result. 3043 3044**Atomic service API**: This API can be used in atomic services since API version 12. 3045 3046**System capability**: SystemCapability.Request.FileTransferAgent 3047 3048**Parameters** 3049 3050| Name| Type| Mandatory| Description| 3051| -------- | -------- | -------- | -------- | 3052| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3053| callback | function | Yes| Callback used to return the data structure of the task response header.| 3054 3055**Error codes** 3056 3057For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3058 3059| ID| Error Message| 3060| -------- | -------- | 3061| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3062 3063**Example** 3064 3065 ```ts 3066 import { BusinessError } from '@kit.BasicServicesKit'; 3067 3068 let attachments: Array<request.agent.FormItem> = [{ 3069 name: "taskOnTest", 3070 value: { 3071 filename: "taskOnTest.avi", 3072 mimeType: "application/octet-stream", 3073 path: "./taskOnTest.avi", 3074 } 3075 }]; 3076 let config: request.agent.Config = { 3077 action: request.agent.Action.UPLOAD, 3078 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3079 title: 'taskOnTest', 3080 description: 'Sample code for event listening', 3081 mode: request.agent.Mode.FOREGROUND, 3082 overwrite: false, 3083 method: "PUT", 3084 data: attachments, 3085 saveas: "./", 3086 network: request.agent.Network.CELLULAR, 3087 metered: false, 3088 roaming: true, 3089 retry: true, 3090 redirect: true, 3091 index: 0, 3092 begins: 0, 3093 ends: -1, 3094 gauge: false, 3095 precise: false, 3096 token: "it is a secret" 3097 }; 3098 let createOnCallback = (response: request.agent.HttpResponse) => { 3099 console.info('upload task response.'); 3100 }; 3101 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3102 task.on('response', createOnCallback); 3103 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3104 task.start(); 3105 }).catch((err: BusinessError) => { 3106 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3107 }); 3108 ``` 3109 3110> **NOTE** 3111> 3112> 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). 3113 3114### off('progress')<sup>10+</sup> 3115 3116off(event: 'progress', callback?: (progress: Progress) => void): void 3117 3118Unsubscribes from task progress events. 3119 3120**Atomic service API**: This API can be used in atomic services since API version 11. 3121 3122**System capability**: SystemCapability.Request.FileTransferAgent 3123 3124**Parameters** 3125 3126| Name| Type| Mandatory| Description| 3127| -------- | -------- | -------- | -------- | 3128| event | string | Yes| Type of the event to subscribe to.<br>The value is **'progress'**, indicating the task progress.| 3129| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3130 3131**Error codes** 3132 3133For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3134 3135| ID| Error Message| 3136| -------- | -------- | 3137| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3138 3139**Example** 3140 3141 ```ts 3142 import { BusinessError } from '@kit.BasicServicesKit'; 3143 3144 let attachments: Array<request.agent.FormItem> = [{ 3145 name: "taskOffTest", 3146 value: { 3147 filename: "taskOffTest.avi", 3148 mimeType: "application/octet-stream", 3149 path: "./taskOffTest.avi", 3150 } 3151 }]; 3152 let config: request.agent.Config = { 3153 action: request.agent.Action.UPLOAD, 3154 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3155 title: 'taskOffTest', 3156 description: 'Sample code for event listening', 3157 mode: request.agent.Mode.FOREGROUND, 3158 overwrite: false, 3159 method: "PUT", 3160 data: attachments, 3161 saveas: "./", 3162 network: request.agent.Network.CELLULAR, 3163 metered: false, 3164 roaming: true, 3165 retry: true, 3166 redirect: true, 3167 index: 0, 3168 begins: 0, 3169 ends: -1, 3170 gauge: false, 3171 precise: false, 3172 token: "it is a secret" 3173 }; 3174 let createOffCallback1 = (progress: request.agent.Progress) => { 3175 console.info('upload task progress.'); 3176 }; 3177 let createOffCallback2 = (progress: request.agent.Progress) => { 3178 console.info('upload task progress.'); 3179 }; 3180 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3181 task.on('progress', createOffCallback1); 3182 task.on('progress', createOffCallback2); 3183 // Unsubscribe from createOffCallback1. 3184 task.off('progress', createOffCallback1); 3185 // Unsubscribe from all callbacks of task progress changes. 3186 task.off('progress'); 3187 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3188 task.start(); 3189 }).catch((err: BusinessError) => { 3190 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3191 }); 3192 ``` 3193 3194> **NOTE** 3195> 3196> 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). 3197 3198### off('completed')<sup>10+</sup> 3199 3200off(event: 'completed', callback?: (progress: Progress) => void): void 3201 3202Unsubscribes from task completion events. 3203 3204**Atomic service API**: This API can be used in atomic services since API version 11. 3205 3206**System capability**: SystemCapability.Request.FileTransferAgent 3207 3208**Parameters** 3209 3210| Name| Type| Mandatory| Description| 3211| -------- | -------- | -------- | -------- | 3212| event | string | Yes| Type of the event to subscribe to.<br>The value is **'completed'**, indicating task completion.| 3213| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3214 3215**Error codes** 3216 3217For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3218 3219| ID| Error Message| 3220| -------- | -------- | 3221| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3222 3223**Example** 3224 3225 ```ts 3226 import { BusinessError } from '@kit.BasicServicesKit'; 3227 3228 let attachments: Array<request.agent.FormItem> = [{ 3229 name: "taskOffTest", 3230 value: { 3231 filename: "taskOffTest.avi", 3232 mimeType: "application/octet-stream", 3233 path: "./taskOffTest.avi", 3234 } 3235 }]; 3236 let config: request.agent.Config = { 3237 action: request.agent.Action.UPLOAD, 3238 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3239 title: 'taskOffTest', 3240 description: 'Sample code for event listening', 3241 mode: request.agent.Mode.FOREGROUND, 3242 overwrite: false, 3243 method: "PUT", 3244 data: attachments, 3245 saveas: "./", 3246 network: request.agent.Network.CELLULAR, 3247 metered: false, 3248 roaming: true, 3249 retry: true, 3250 redirect: true, 3251 index: 0, 3252 begins: 0, 3253 ends: -1, 3254 gauge: false, 3255 precise: false, 3256 token: "it is a secret" 3257 }; 3258 let createOffCallback1 = (progress: request.agent.Progress) => { 3259 console.info('upload task completed.'); 3260 }; 3261 let createOffCallback2 = (progress: request.agent.Progress) => { 3262 console.info('upload task completed.'); 3263 }; 3264 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3265 task.on('completed', createOffCallback1); 3266 task.on('completed', createOffCallback2); 3267 // Unsubscribe from createOffCallback1. 3268 task.off('completed', createOffCallback1); 3269 // Unsubscribe from all callbacks of the task completion events. 3270 task.off('completed'); 3271 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3272 task.start(); 3273 }).catch((err: BusinessError) => { 3274 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3275 }); 3276 ``` 3277 3278> **NOTE** 3279> 3280> 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). 3281 3282### off('failed')<sup>10+</sup> 3283 3284off(event: 'failed', callback?: (progress: Progress) => void): void 3285 3286Unsubscribes from task failure events. 3287 3288**Atomic service API**: This API can be used in atomic services since API version 11. 3289 3290**System capability**: SystemCapability.Request.FileTransferAgent 3291 3292**Parameters** 3293 3294| Name| Type| Mandatory| Description| 3295| -------- | -------- | -------- | -------- | 3296| event | string | Yes| Type of the event to subscribe to.<br>The value is **'failed'**, indicating task failure.| 3297| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3298 3299**Error codes** 3300 3301For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3302 3303| ID| Error Message| 3304| -------- | -------- | 3305| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3306 3307**Example** 3308 3309 ```ts 3310 import { BusinessError } from '@kit.BasicServicesKit'; 3311 3312 let attachments: Array<request.agent.FormItem> = [{ 3313 name: "taskOffTest", 3314 value: { 3315 filename: "taskOffTest.avi", 3316 mimeType: "application/octet-stream", 3317 path: "./taskOffTest.avi", 3318 } 3319 }]; 3320 let config: request.agent.Config = { 3321 action: request.agent.Action.UPLOAD, 3322 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3323 title: 'taskOffTest', 3324 description: 'Sample code for event listening', 3325 mode: request.agent.Mode.FOREGROUND, 3326 overwrite: false, 3327 method: "PUT", 3328 data: attachments, 3329 saveas: "./", 3330 network: request.agent.Network.CELLULAR, 3331 metered: false, 3332 roaming: true, 3333 retry: true, 3334 redirect: true, 3335 index: 0, 3336 begins: 0, 3337 ends: -1, 3338 gauge: false, 3339 precise: false, 3340 token: "it is a secret" 3341 }; 3342 let createOffCallback1 = (progress: request.agent.Progress) => { 3343 console.info('upload task failed.'); 3344 }; 3345 let createOffCallback2 = (progress: request.agent.Progress) => { 3346 console.info('upload task failed.'); 3347 }; 3348 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3349 task.on('failed', createOffCallback1); 3350 task.on('failed', createOffCallback2); 3351 // Unsubscribe from createOffCallback1. 3352 task.off('failed', createOffCallback1); 3353 // Unsubscribe from all callbacks of the task failure events. 3354 task.off('failed'); 3355 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3356 task.start(); 3357 }).catch((err: BusinessError) => { 3358 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3359 }); 3360 ``` 3361 3362> **NOTE** 3363> 3364> 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). 3365 3366### off('pause')<sup>11+</sup> 3367 3368off(event: 'pause', callback?: (progress: Progress) => void): void 3369 3370Unsubscribes from the foreground task pause event. 3371 3372**System capability**: SystemCapability.Request.FileTransferAgent 3373 3374**Parameters** 3375 3376| Name| Type| Mandatory| Description| 3377| -------- | -------- | -------- | -------- | 3378| event | string | Yes| Type of the event to subscribe to.<br>The value is **'pause'**, indicating task pause.| 3379| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3380 3381**Error codes** 3382 3383For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3384 3385| ID| Error Message| 3386| -------- | -------- | 3387| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3388 3389**Example** 3390 3391 ```ts 3392 import { BusinessError } from '@kit.BasicServicesKit'; 3393 3394 let attachments: Array<request.agent.FormItem> = [{ 3395 name: "taskOffTest", 3396 value: { 3397 filename: "taskOffTest.avi", 3398 mimeType: "application/octet-stream", 3399 path: "./taskOffTest.avi", 3400 } 3401 }]; 3402 let config: request.agent.Config = { 3403 action: request.agent.Action.UPLOAD, 3404 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3405 title: 'taskOffTest', 3406 description: 'Sample code for event listening', 3407 mode: request.agent.Mode.FOREGROUND, 3408 overwrite: false, 3409 method: "PUT", 3410 data: attachments, 3411 saveas: "./", 3412 network: request.agent.Network.CELLULAR, 3413 metered: false, 3414 roaming: true, 3415 retry: true, 3416 redirect: true, 3417 index: 0, 3418 begins: 0, 3419 ends: -1, 3420 gauge: false, 3421 precise: false, 3422 token: "it is a secret" 3423 }; 3424 let createOffCallback1 = (progress: request.agent.Progress) => { 3425 console.info('upload task pause.'); 3426 }; 3427 let createOffCallback2 = (progress: request.agent.Progress) => { 3428 console.info('upload task pause.'); 3429 }; 3430 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3431 task.on('pause', createOffCallback1); 3432 task.on('pause', createOffCallback2); 3433 // Unsubscribe from createOffCallback1. 3434 task.off('pause', createOffCallback1); 3435 // Unsubscribe from all callbacks of the foreground task pause event. 3436 task.off('pause'); 3437 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3438 task.start(); 3439 }).catch((err: BusinessError) => { 3440 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3441 }); 3442 ``` 3443 3444> **NOTE** 3445> 3446> 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). 3447 3448### off('resume')<sup>11+</sup> 3449 3450off(event: 'resume', callback?: (progress: Progress) => void): void 3451 3452Unsubscribes from the foreground task resume event. 3453 3454**System capability**: SystemCapability.Request.FileTransferAgent 3455 3456**Parameters** 3457 3458| Name| Type| Mandatory| Description| 3459| -------- | -------- | -------- | -------- | 3460| event | string | Yes| Type of the event to subscribe to.<br>The value is **'resume'**, indicating task resume.| 3461| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3462 3463**Error codes** 3464 3465For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3466 3467| ID| Error Message| 3468| -------- | -------- | 3469| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3470 3471**Example** 3472 3473 ```ts 3474 import { BusinessError } from '@kit.BasicServicesKit'; 3475 3476 let attachments: Array<request.agent.FormItem> = [{ 3477 name: "taskOffTest", 3478 value: { 3479 filename: "taskOffTest.avi", 3480 mimeType: "application/octet-stream", 3481 path: "./taskOffTest.avi", 3482 } 3483 }]; 3484 let config: request.agent.Config = { 3485 action: request.agent.Action.UPLOAD, 3486 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3487 title: 'taskOffTest', 3488 description: 'Sample code for event listening', 3489 mode: request.agent.Mode.FOREGROUND, 3490 overwrite: false, 3491 method: "PUT", 3492 data: attachments, 3493 saveas: "./", 3494 network: request.agent.Network.CELLULAR, 3495 metered: false, 3496 roaming: true, 3497 retry: true, 3498 redirect: true, 3499 index: 0, 3500 begins: 0, 3501 ends: -1, 3502 gauge: false, 3503 precise: false, 3504 token: "it is a secret" 3505 }; 3506 let createOffCallback1 = (progress: request.agent.Progress) => { 3507 console.info('upload task resume.'); 3508 }; 3509 let createOffCallback2 = (progress: request.agent.Progress) => { 3510 console.info('upload task resume.'); 3511 }; 3512 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3513 task.on('resume', createOffCallback1); 3514 task.on('resume', createOffCallback2); 3515 // Unsubscribe from createOffCallback1. 3516 task.off('resume', createOffCallback1); 3517 // Unsubscribe from all callbacks of the foreground task resume event. 3518 task.off('resume'); 3519 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3520 task.start(); 3521 }).catch((err: BusinessError) => { 3522 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3523 }); 3524 ``` 3525 3526> **NOTE** 3527> 3528> 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). 3529 3530### off('remove')<sup>11+</sup> 3531 3532off(event: 'remove', callback?: (progress: Progress) => void): void 3533 3534Unsubscribes from the task removal event. 3535 3536**System capability**: SystemCapability.Request.FileTransferAgent 3537 3538**Parameters** 3539 3540| Name| Type| Mandatory| Description| 3541| -------- | -------- | -------- | -------- | 3542| event | string | Yes| Type of the event to subscribe to.<br>The value is **'remove'**, indicating task removal.| 3543| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3544 3545**Error codes** 3546 3547For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3548 3549| ID| Error Message| 3550| -------- | -------- | 3551| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3552 3553**Example** 3554 3555 ```ts 3556 import { BusinessError } from '@kit.BasicServicesKit'; 3557 3558 let attachments: Array<request.agent.FormItem> = [{ 3559 name: "taskOffTest", 3560 value: { 3561 filename: "taskOffTest.avi", 3562 mimeType: "application/octet-stream", 3563 path: "./taskOffTest.avi", 3564 } 3565 }]; 3566 let config: request.agent.Config = { 3567 action: request.agent.Action.UPLOAD, 3568 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3569 title: 'taskOffTest', 3570 description: 'Sample code for event listening', 3571 mode: request.agent.Mode.FOREGROUND, 3572 overwrite: false, 3573 method: "PUT", 3574 data: attachments, 3575 saveas: "./", 3576 network: request.agent.Network.CELLULAR, 3577 metered: false, 3578 roaming: true, 3579 retry: true, 3580 redirect: true, 3581 index: 0, 3582 begins: 0, 3583 ends: -1, 3584 gauge: false, 3585 precise: false, 3586 token: "it is a secret" 3587 }; 3588 let createOffCallback1 = (progress: request.agent.Progress) => { 3589 console.info('upload task remove.'); 3590 }; 3591 let createOffCallback2 = (progress: request.agent.Progress) => { 3592 console.info('upload task remove.'); 3593 }; 3594 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3595 task.on('remove', createOffCallback1); 3596 task.on('remove', createOffCallback2); 3597 // Unsubscribe from createOffCallback1. 3598 task.off('remove', createOffCallback1); 3599 // Unsubscribe from all callbacks of the task removal event. 3600 task.off('remove'); 3601 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3602 task.start(); 3603 }).catch((err: BusinessError) => { 3604 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3605 }); 3606 ``` 3607 3608> **NOTE** 3609> 3610> 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). 3611 3612### off('response')<sup>12+</sup> 3613 3614off(event: 'response', callback?: Callback<HttpResponse>): void 3615 3616Unsubscribes from task response headers. 3617 3618**Atomic service API**: This API can be used in atomic services since API version 12. 3619 3620**System capability**: SystemCapability.Request.FileTransferAgent 3621 3622**Parameters** 3623 3624| Name| Type| Mandatory| Description| 3625| -------- | -------- | -------- | -------- | 3626| event | string | Yes| Type of the event to subscribe to.<br>The value is **response**, which indicates the task response.| 3627| callback | function | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| 3628 3629**Error codes** 3630 3631For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 3632 3633| ID| Error Message| 3634| -------- | -------- | 3635| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 3636 3637**Example** 3638 3639 ```ts 3640 import { BusinessError } from '@kit.BasicServicesKit'; 3641 3642 let attachments: Array<request.agent.FormItem> = [{ 3643 name: "taskOffTest", 3644 value: { 3645 filename: "taskOffTest.avi", 3646 mimeType: "application/octet-stream", 3647 path: "./taskOffTest.avi", 3648 } 3649 }]; 3650 let config: request.agent.Config = { 3651 action: request.agent.Action.UPLOAD, 3652 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3653 title: 'taskOffTest', 3654 description: 'Sample code for event listening', 3655 mode: request.agent.Mode.FOREGROUND, 3656 overwrite: false, 3657 method: "PUT", 3658 data: attachments, 3659 saveas: "./", 3660 network: request.agent.Network.CELLULAR, 3661 metered: false, 3662 roaming: true, 3663 retry: true, 3664 redirect: true, 3665 index: 0, 3666 begins: 0, 3667 ends: -1, 3668 gauge: false, 3669 precise: false, 3670 token: "it is a secret" 3671 }; 3672 let createOffCallback1 = (progress: request.agent.HttpResponse) => { 3673 console.info('upload task response.'); 3674 }; 3675 let createOffCallback2 = (progress: request.agent.HttpResponse) => { 3676 console.info('upload task response.'); 3677 }; 3678 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3679 task.on('response', createOffCallback1); 3680 task.on('response', createOffCallback2); 3681 // Unsubscribe from createOffCallback1. 3682 task.off('response', createOffCallback1); 3683 // Unsubscribe from all callbacks of the task removal event. 3684 task.off('response'); 3685 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 3686 task.start(); 3687 }).catch((err: BusinessError) => { 3688 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3689 }); 3690 ``` 3691 3692> **NOTE** 3693> 3694> 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). 3695 3696### start<sup>10+</sup> 3697 3698start(callback: AsyncCallback<void>): void 3699 3700Tasks in the following states can be started: 37011. Task created by **request.agent.create**. 37022. Download tasks that are created by **request.agent.create** but have failed or stopped 3703 3704**Required permissions**: ohos.permission.INTERNET 3705 3706**Atomic service API**: This API can be used in atomic services since API version 11. 3707 3708**System capability**: SystemCapability.Request.FileTransferAgent 3709 3710**Parameters** 3711 3712| Name| Type| Mandatory| Description| 3713| -------- | -------- | -------- | -------- | 3714| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3715 3716**Error codes** 3717 3718For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3719 3720| ID| Error Message| 3721| -------- | -------- | 3722| 201 | Permission denied. | 3723| 13400003 | task service ability error. | 3724| 21900007 | task state error. | 3725 3726**Example** 3727 3728 ```ts 3729 import { BusinessError } from '@kit.BasicServicesKit'; 3730 3731 let config: request.agent.Config = { 3732 action: request.agent.Action.DOWNLOAD, 3733 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3734 title: 'taskStartTest', 3735 description: 'Sample code for start the download task', 3736 mode: request.agent.Mode.BACKGROUND, 3737 overwrite: false, 3738 method: "GET", 3739 data: "", 3740 saveas: "./", 3741 network: request.agent.Network.CELLULAR, 3742 metered: false, 3743 roaming: true, 3744 retry: true, 3745 redirect: true, 3746 index: 0, 3747 begins: 0, 3748 ends: -1, 3749 gauge: false, 3750 precise: false, 3751 token: "it is a secret" 3752 }; 3753 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3754 task.start((err: BusinessError) => { 3755 if (err) { 3756 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3757 return; 3758 } 3759 console.info(`Succeeded in starting a download task.`); 3760 }); 3761 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3762 }).catch((err: BusinessError) => { 3763 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3764 }); 3765 ``` 3766 3767> **NOTE** 3768> 3769> 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). 3770 3771### start<sup>10+</sup> 3772 3773start(): Promise<void> 3774 3775Tasks in the following states can be started: 37761. Task created by **request.agent.create**. 37772. Download tasks that are created by **request.agent.create** but have failed or stopped 3778 3779**Required permissions**: ohos.permission.INTERNET 3780 3781**Atomic service API**: This API can be used in atomic services since API version 11. 3782 3783**System capability**: SystemCapability.Request.FileTransferAgent 3784 3785**Return value** 3786 3787| Type | Description | 3788| ------------------- | ------------------------- | 3789| Promise<void> | Promise that returns no value.| 3790 3791**Error codes** 3792 3793For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3794 3795| ID| Error Message| 3796| -------- | -------- | 3797| 201 | Permission denied. | 3798| 13400003 | task service ability error. | 3799| 21900007 | task state error. | 3800 3801**Example** 3802 3803 ```ts 3804 import { BusinessError } from '@kit.BasicServicesKit'; 3805 3806 let config: request.agent.Config = { 3807 action: request.agent.Action.DOWNLOAD, 3808 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3809 title: 'taskStartTest', 3810 description: 'Sample code for start the download task', 3811 mode: request.agent.Mode.BACKGROUND, 3812 overwrite: false, 3813 method: "GET", 3814 data: "", 3815 saveas: "./", 3816 network: request.agent.Network.CELLULAR, 3817 metered: false, 3818 roaming: true, 3819 retry: true, 3820 redirect: true, 3821 index: 0, 3822 begins: 0, 3823 ends: -1, 3824 gauge: false, 3825 precise: false, 3826 token: "it is a secret" 3827 }; 3828 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3829 task.start().then(() => { 3830 console.info(`Succeeded in starting a download task.`); 3831 }).catch((err: BusinessError) => { 3832 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 3833 }); 3834 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3835 }).catch((err: BusinessError) => { 3836 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3837 }); 3838 ``` 3839 3840> **NOTE** 3841> 3842> 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). 3843 3844### pause<sup>10+</sup> 3845 3846pause(callback: AsyncCallback<void>): void 3847 3848Pauses a task that is waiting, running, or retrying. This API uses an asynchronous callback to return the result. 3849 3850**System capability**: SystemCapability.Request.FileTransferAgent 3851 3852**Parameters** 3853 3854| Name| Type| Mandatory| Description| 3855| -------- | -------- | -------- | -------- | 3856| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3857 3858**Error codes** 3859 3860For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3861 3862| ID| Error Message| 3863| -------- | -------- | 3864| 13400003 | task service ability error. | 3865| 21900007 | task state error. | 3866 3867**Example** 3868 3869 ```ts 3870 import { BusinessError } from '@kit.BasicServicesKit'; 3871 3872 let config: request.agent.Config = { 3873 action: request.agent.Action.DOWNLOAD, 3874 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3875 title: 'taskPauseTest', 3876 description: 'Sample code for pause the download task', 3877 mode: request.agent.Mode.BACKGROUND, 3878 overwrite: false, 3879 method: "GET", 3880 data: "", 3881 saveas: "./", 3882 network: request.agent.Network.CELLULAR, 3883 metered: false, 3884 roaming: true, 3885 retry: true, 3886 redirect: true, 3887 index: 0, 3888 begins: 0, 3889 ends: -1, 3890 gauge: false, 3891 precise: false, 3892 token: "it is a secret" 3893 }; 3894 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3895 task.start(); 3896 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3897 task.pause((err: BusinessError) => { 3898 if (err) { 3899 console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); 3900 return; 3901 } 3902 console.info(`Succeeded in pausing a download task. `); 3903 }); 3904 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3905 }).catch((err: BusinessError) => { 3906 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 3907 }); 3908 ``` 3909 3910### pause<sup>10+</sup> 3911 3912pause(): Promise<void> 3913 3914Pauses a task that is waiting, running, or retrying. This API uses a promise to return the result. 3915 3916**System capability**: SystemCapability.Request.FileTransferAgent 3917 3918**Return value** 3919 3920| Type | Description | 3921| ------------------- | ------------------------- | 3922| Promise<void> | Promise that returns no value.| 3923 3924**Error codes** 3925 3926For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 3927 3928| ID| Error Message| 3929| -------- | -------- | 3930| 13400003 | task service ability error. | 3931| 21900007 | task state error. | 3932 3933**Example** 3934 3935 ```ts 3936 import { BusinessError } from '@kit.BasicServicesKit'; 3937 3938 let config: request.agent.Config = { 3939 action: request.agent.Action.DOWNLOAD, 3940 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 3941 title: 'taskPauseTest', 3942 description: 'Sample code for pause the download task', 3943 mode: request.agent.Mode.BACKGROUND, 3944 overwrite: false, 3945 method: "GET", 3946 data: "", 3947 saveas: "./", 3948 network: request.agent.Network.CELLULAR, 3949 metered: false, 3950 roaming: true, 3951 retry: true, 3952 redirect: true, 3953 index: 0, 3954 begins: 0, 3955 ends: -1, 3956 gauge: false, 3957 precise: false, 3958 token: "it is a secret" 3959 }; 3960 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 3961 task.start(); 3962 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 3963 task.pause().then(() => { 3964 console.info(`Succeeded in pausing a download task. `); 3965 }).catch((err: BusinessError) => { 3966 console.error(`Failed to pause the upload task, Code: ${err.code}, message: ${err.message}`); 3967 }); 3968 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 3969 }).catch((err: BusinessError) => { 3970 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 3971 }); 3972 ``` 3973 3974### resume<sup>10+</sup> 3975 3976resume(callback: AsyncCallback<void>): void 3977 3978Resumes a paused task. This API uses an asynchronous callback to return the result. 3979 3980**Required permissions**: ohos.permission.INTERNET 3981 3982**System capability**: SystemCapability.Request.FileTransferAgent 3983 3984**Parameters** 3985 3986| Name| Type| Mandatory| Description| 3987| -------- | -------- | -------- | -------- | 3988| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3989 3990**Error codes** 3991 3992For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 3993 3994| ID| Error Message| 3995| -------- | -------- | 3996| 201 | Permission denied. | 3997| 13400003 | task service ability error. | 3998| 21900007 | task state error. | 3999 4000**Example** 4001 4002 ```ts 4003 import { BusinessError } from '@kit.BasicServicesKit'; 4004 4005 let config: request.agent.Config = { 4006 action: request.agent.Action.DOWNLOAD, 4007 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4008 title: 'taskResumeTest', 4009 description: 'Sample code for resume the download task', 4010 mode: request.agent.Mode.BACKGROUND, 4011 overwrite: false, 4012 method: "GET", 4013 data: "", 4014 saveas: "./", 4015 network: request.agent.Network.CELLULAR, 4016 metered: false, 4017 roaming: true, 4018 retry: true, 4019 redirect: true, 4020 index: 0, 4021 begins: 0, 4022 ends: -1, 4023 gauge: false, 4024 precise: false, 4025 token: "it is a secret" 4026 }; 4027 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4028 task.start(); 4029 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4030 task.pause(); 4031 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4032 task.resume((err: BusinessError) => { 4033 if (err) { 4034 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4035 return; 4036 } 4037 console.info(`Succeeded in resuming a download task. `); 4038 }); 4039 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4040 }).catch((err: BusinessError) => { 4041 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4042 }); 4043 ``` 4044 4045### resume<sup>10+</sup> 4046 4047resume(): Promise<void> 4048 4049Resumes a paused task. This API uses a promise to return the result. 4050 4051**Required permissions**: ohos.permission.INTERNET 4052 4053**System capability**: SystemCapability.Request.FileTransferAgent 4054 4055**Return value** 4056 4057| Type | Description | 4058| ------------------- | ------------------------- | 4059| Promise<void> | Promise that returns no value.| 4060 4061**Error codes** 4062 4063For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4064 4065| ID| Error Message| 4066| -------- | -------- | 4067| 201 | Permission denied. | 4068| 13400003 | task service ability error. | 4069| 21900007 | task state error. | 4070 4071**Example** 4072 4073 ```ts 4074 import { BusinessError } from '@kit.BasicServicesKit'; 4075 4076 let config: request.agent.Config = { 4077 action: request.agent.Action.DOWNLOAD, 4078 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4079 title: 'taskResumeTest', 4080 description: 'Sample code for resume the download task', 4081 mode: request.agent.Mode.BACKGROUND, 4082 overwrite: false, 4083 method: "GET", 4084 data: "", 4085 saveas: "./", 4086 network: request.agent.Network.CELLULAR, 4087 metered: false, 4088 roaming: true, 4089 retry: true, 4090 redirect: true, 4091 index: 0, 4092 begins: 0, 4093 ends: -1, 4094 gauge: false, 4095 precise: false, 4096 token: "it is a secret" 4097 }; 4098 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4099 task.start(); 4100 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4101 task.pause(); 4102 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4103 task.resume().then(() => { 4104 console.info(`Succeeded in resuming a download task. `); 4105 }).catch((err: BusinessError) => { 4106 console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); 4107 }); 4108 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4109 }).catch((err: BusinessError) => { 4110 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4111 }); 4112 ``` 4113 4114### stop<sup>10+</sup> 4115 4116stop(callback: AsyncCallback<void>): void 4117 4118Stops 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. 4119 4120**Atomic service API**: This API can be used in atomic services since API version 11. 4121 4122**System capability**: SystemCapability.Request.FileTransferAgent 4123 4124**Parameters** 4125 4126| Name| Type| Mandatory| Description| 4127| -------- | -------- | -------- | -------- | 4128| callback | function | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4129 4130**Error codes** 4131 4132For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4133 4134| ID| Error Message| 4135| -------- | -------- | 4136| 13400003 | task service ability error. | 4137| 21900007 | task state error. | 4138 4139**Example** 4140 4141 ```ts 4142 import { BusinessError } from '@kit.BasicServicesKit'; 4143 4144 let config: request.agent.Config = { 4145 action: request.agent.Action.DOWNLOAD, 4146 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4147 title: 'taskStopTest', 4148 description: 'Sample code for stop the download task', 4149 mode: request.agent.Mode.BACKGROUND, 4150 overwrite: false, 4151 method: "GET", 4152 data: "", 4153 saveas: "./", 4154 network: request.agent.Network.CELLULAR, 4155 metered: false, 4156 roaming: true, 4157 retry: true, 4158 redirect: true, 4159 index: 0, 4160 begins: 0, 4161 ends: -1, 4162 gauge: false, 4163 precise: false, 4164 token: "it is a secret" 4165 }; 4166 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4167 task.start(); 4168 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4169 task.stop((err: BusinessError) => { 4170 if (err) { 4171 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4172 return; 4173 } 4174 console.info(`Succeeded in stopping a download task. `); 4175 }); 4176 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4177 }).catch((err: BusinessError) => { 4178 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4179 }); 4180 ``` 4181 4182 4183### stop<sup>10+</sup> 4184 4185stop(): Promise<void> 4186 4187Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. 4188 4189**Atomic service API**: This API can be used in atomic services since API version 11. 4190 4191**System capability**: SystemCapability.Request.FileTransferAgent 4192 4193**Return value** 4194 4195| Type | Description | 4196| ------------------- | ------------------------- | 4197| Promise<void> | Promise that returns no value.| 4198 4199**Error codes** 4200 4201For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). 4202 4203| ID| Error Message| 4204| -------- | -------- | 4205| 13400003 | task service ability error. | 4206| 21900007 | task state error. | 4207 4208**Example** 4209 4210 ```ts 4211 import { BusinessError } from '@kit.BasicServicesKit'; 4212 4213 let config: request.agent.Config = { 4214 action: request.agent.Action.DOWNLOAD, 4215 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4216 title: 'taskStopTest', 4217 description: 'Sample code for stop the download task', 4218 mode: request.agent.Mode.BACKGROUND, 4219 overwrite: false, 4220 method: "GET", 4221 data: "", 4222 saveas: "./", 4223 network: request.agent.Network.CELLULAR, 4224 metered: false, 4225 roaming: true, 4226 retry: true, 4227 redirect: true, 4228 index: 0, 4229 begins: 0, 4230 ends: -1, 4231 gauge: false, 4232 precise: false, 4233 token: "it is a secret" 4234 }; 4235 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4236 task.start(); 4237 for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. 4238 task.stop().then(() => { 4239 console.info(`Succeeded in stopping a download task. `); 4240 }).catch((err: BusinessError) => { 4241 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 4242 }); 4243 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 4244 }).catch((err: BusinessError) => { 4245 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4246 }); 4247 ``` 4248 4249## request.agent.create<sup>10+</sup> 4250 4251create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void 4252 4253Creates an upload or download task and adds it to the queue. This API uses an asynchronous callback to return the result. 4254 4255 4256**Required permissions**: ohos.permission.INTERNET 4257 4258**Atomic service API**: This API can be used in atomic services since API version 11. 4259 4260**System capability**: SystemCapability.Request.FileTransferAgent 4261 4262**Parameters** 4263 4264| Name| Type| Mandatory| Description| 4265| -------- | -------- | -------- | -------- | 4266| config | [Config](#config10) | Yes| Task configuration.| 4267| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4268| callback | AsyncCallback<[Task](#task10)> | Yes| Callback used to return the configuration about the created task.| 4269 4270**Error codes** 4271 4272For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4273 4274| ID| Error Message| 4275| -------- | -------- | 4276| 201 | permission denied. | 4277| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4278| 13400001 | file operation error. | 4279| 13400003 | task service ability error. | 4280| 21900004 | the application task queue is full. | 4281| 21900005 | task mode error. | 4282 4283**Example** 4284 4285 ```ts 4286 import { BusinessError } from '@kit.BasicServicesKit'; 4287 4288 let attachments: Array<request.agent.FormItem> = [{ 4289 name: "createTest", 4290 value: { 4291 filename: "createTest.avi", 4292 mimeType: "application/octet-stream", 4293 path: "./createTest.avi", 4294 } 4295 }]; 4296 let config: request.agent.Config = { 4297 action: request.agent.Action.UPLOAD, 4298 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4299 title: 'createTest', 4300 description: 'Sample code for create task', 4301 mode: request.agent.Mode.BACKGROUND, 4302 overwrite: false, 4303 method: "PUT", 4304 data: attachments, 4305 saveas: "./", 4306 network: request.agent.Network.CELLULAR, 4307 metered: false, 4308 roaming: true, 4309 retry: true, 4310 redirect: true, 4311 index: 0, 4312 begins: 0, 4313 ends: -1, 4314 gauge: false, 4315 precise: false, 4316 token: "it is a secret" 4317 }; 4318 request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => { 4319 if (err) { 4320 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4321 return; 4322 } 4323 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4324 task.start(); 4325 }); 4326 ``` 4327 4328> **NOTE** 4329> 4330> 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). 4331 4332## request.agent.create<sup>10+</sup> 4333 4334create(context: BaseContext, config: Config): Promise<Task> 4335 4336Creates an upload or download task and adds it to the queue. This API uses a promise to return the result. 4337 4338 4339**Required permissions**: ohos.permission.INTERNET 4340 4341**Atomic service API**: This API can be used in atomic services since API version 11. 4342 4343**System capability**: SystemCapability.Request.FileTransferAgent 4344 4345**Parameters** 4346 4347| Name| Type| Mandatory| Description| 4348| -------- | -------- | -------- | -------- | 4349| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4350| config | [Config](#config10) | Yes| Task configuration.| 4351 4352**Return value** 4353 4354| Type | Description | 4355| ------------------- | ------------------------- | 4356| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4357 4358**Error codes** 4359 4360For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4361 4362| ID| Error Message| 4363| -------- | -------- | 4364| 201 | permission denied. | 4365| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4366| 13400001 | file operation error. | 4367| 13400003 | task service ability error. | 4368| 21900004 | the application task queue is full. | 4369| 21900005 | task mode error. | 4370 4371**Example** 4372 4373 ```ts 4374 import { BusinessError } from '@kit.BasicServicesKit'; 4375 4376 let attachments: Array<request.agent.FormItem> = [{ 4377 name: "createTest", 4378 value: { 4379 filename: "createTest.avi", 4380 mimeType: "application/octet-stream", 4381 path: "./createTest.avi", 4382 } 4383 }]; 4384 let config: request.agent.Config = { 4385 action: request.agent.Action.UPLOAD, 4386 url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. 4387 title: 'createTest', 4388 description: 'Sample code for create task', 4389 mode: request.agent.Mode.BACKGROUND, 4390 overwrite: false, 4391 method: "PUT", 4392 data: attachments, 4393 saveas: "./", 4394 network: request.agent.Network.CELLULAR, 4395 metered: false, 4396 roaming: true, 4397 retry: true, 4398 redirect: true, 4399 index: 0, 4400 begins: 0, 4401 ends: -1, 4402 gauge: false, 4403 precise: false, 4404 token: "it is a secret" 4405 }; 4406 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 4407 console.info(`Succeeded in creating a download task. result: ${task.config}`); 4408 task.start(); 4409 }).catch((err: BusinessError) => { 4410 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 4411 }); 4412 ``` 4413 4414> **NOTE** 4415> 4416> 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). 4417 4418## request.agent.getTask<sup>11+</sup> 4419 4420getTask(context: BaseContext, id: string, token?: string): Promise<Task> 4421 4422Obtains task information based on the task ID. This API uses a promise to return the result. 4423 4424**System capability**: SystemCapability.Request.FileTransferAgent 4425 4426**Parameters** 4427 4428| Name| Type| Mandatory| Description| 4429| -------- | -------- | -------- | -------- | 4430| context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Application-based context.| 4431| id | string | Yes| Task ID.| 4432| token | string | No| Token for task query.| 4433 4434**Return value** 4435 4436| Type | Description | 4437| ------------------- | ------------------------- | 4438| Promise<[Task](#task10)> | Promise used to return the configuration about the created task.| 4439 4440**Error codes** 4441 4442For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4443 4444| ID| Error Message| 4445| -------- | -------- | 4446| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed | 4447| 13400003 | task service ability error. | 4448| 21900006 | task not found. | 4449 4450**Example** 4451 4452 ```ts 4453 import { BusinessError } from '@kit.BasicServicesKit'; 4454 4455 request.agent.getTask(getContext(), "123456").then((task: request.agent.Task) => { 4456 console.info(`Succeeded in querying a upload task. result: ${task.tid}`); 4457 }).catch((err: BusinessError) => { 4458 console.error(`Failed to query a upload task, Code: ${err.code}, message: ${err.message}`); 4459 }); 4460 ``` 4461 4462## request.agent.remove<sup>10+</sup> 4463 4464remove(id: string, callback: AsyncCallback<void>): void 4465 4466Removes 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. 4467 4468**Atomic service API**: This API can be used in atomic services since API version 11. 4469 4470**System capability**: SystemCapability.Request.FileTransferAgent 4471 4472**Parameters** 4473 4474| Name| Type| Mandatory| Description| 4475| -------- | -------- | -------- | -------- | 4476| id | string | Yes| Task ID.| 4477| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4478 4479**Error codes** 4480 4481For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4482 4483| ID| Error Message| 4484| -------- | -------- | 4485| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4486| 13400003 | task service ability error. | 4487| 21900006 | task not found. | 4488 4489**Example** 4490 4491 ```ts 4492 import { BusinessError } from '@kit.BasicServicesKit'; 4493 4494 request.agent.remove("123456", (err: BusinessError) => { 4495 if (err) { 4496 console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`); 4497 return; 4498 } 4499 console.info(`Succeeded in creating a download task.`); 4500 }); 4501 ``` 4502 4503 4504## request.agent.remove<sup>10+</sup> 4505 4506remove(id: string): Promise<void> 4507 4508Removes 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. 4509 4510**Atomic service API**: This API can be used in atomic services since API version 11. 4511 4512**System capability**: SystemCapability.Request.FileTransferAgent 4513 4514**Parameters** 4515 4516| Name| Type| Mandatory| Description| 4517| -------- | -------- | -------- | -------- | 4518| id | string | Yes| Task ID.| 4519 4520**Return value** 4521 4522| Type | Description | 4523| ------------------- | ------------------------- | 4524| Promise<void> | Promise that returns no value.| 4525 4526**Error codes** 4527 4528For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4529 4530| ID| Error Message| 4531| -------- | -------- | 4532| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4533| 13400003 | task service ability error. | 4534| 21900006 | task not found. | 4535 4536**Example** 4537 4538 ```ts 4539 import { BusinessError } from '@kit.BasicServicesKit'; 4540 4541 request.agent.remove("123456").then(() => { 4542 console.info(`Succeeded in removing a download task. `); 4543 }).catch((err: BusinessError) => { 4544 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 4545 }); 4546 ``` 4547 4548 4549## request.agent.show<sup>10+</sup> 4550 4551show(id: string, callback: AsyncCallback<TaskInfo>): void 4552 4553Queries a task details based on the task ID. This API uses an asynchronous callback to return the result. 4554 4555**System capability**: SystemCapability.Request.FileTransferAgent 4556 4557**Parameters** 4558 4559| Name| Type| Mandatory| Description| 4560| -------- | -------- | -------- | -------- | 4561| id | string | Yes| Task ID.| 4562| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes| Callback used to return task details.| 4563 4564**Error codes** 4565For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4566 4567| ID| Error Message| 4568| -------- | -------- | 4569| 401 | parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type | 4570| 13400003 | task service ability error. | 4571| 21900006 | task not found. | 4572 4573**Example** 4574 4575 ```ts 4576 import { BusinessError } from '@kit.BasicServicesKit'; 4577 4578 request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4579 if (err) { 4580 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4581 return; 4582 } 4583 console.info(`Succeeded in showing a upload task.`); 4584 }); 4585 ``` 4586 4587 4588## request.agent.show<sup>10+</sup> 4589 4590show(id: string): Promise<TaskInfo> 4591 4592Queries a task details based on the task ID. This API uses a promise to return the result. 4593 4594**System capability**: SystemCapability.Request.FileTransferAgent 4595 4596**Parameters** 4597 4598| Name| Type| Mandatory| Description| 4599| -------- | -------- | -------- | -------- | 4600| id | string | Yes| Task ID.| 4601 4602**Return value** 4603 4604| Type | Description | 4605| ------------------- | ------------------------- | 4606| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details.| 4607 4608**Error codes** 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.show("123456").then((taskInfo: request.agent.TaskInfo) => { 4623 console.info(`Succeeded in showing a upload task.`); 4624 }).catch((err: BusinessError) => { 4625 console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); 4626 }); 4627 ``` 4628 4629 4630## request.agent.touch<sup>10+</sup> 4631 4632touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void 4633 4634Queries the task details based on the task ID and token. 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| token | string | Yes| Token for task query.| 4644| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes| Callback used to return task details.| 4645 4646**Error codes** 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 3. Parameter verification failed | 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.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { 4661 if (err) { 4662 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4663 return; 4664 } 4665 console.info(`Succeeded in touching a upload task.`); 4666 }); 4667 ``` 4668 4669 4670## request.agent.touch<sup>10+</sup> 4671 4672touch(id: string, token: string): Promise<TaskInfo> 4673 4674Queries the task details based on the task ID and token. 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| token | string | Yes| Token for task query.| 4684 4685**Return value** 4686 4687| Type | Description | 4688| ------------------- | ------------------------- | 4689| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details.| 4690 4691**Error codes** 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 3. Parameter verification failed | 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.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { 4706 console.info(`Succeeded in touching a upload task. `); 4707 }).catch((err: BusinessError) => { 4708 console.error(`Failed to touch a upload task, Code: ${err.code}, message: ${err.message}`); 4709 }); 4710 ``` 4711 4712## request.agent.search<sup>10+</sup> 4713 4714search(callback: AsyncCallback<Array<string>>): void 4715 4716Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4717 4718**System capability**: SystemCapability.Request.FileTransferAgent 4719 4720**Parameters** 4721 4722| Name| Type| Mandatory| Description| 4723| -------- | -------- | -------- | -------- | 4724| callback | AsyncCallback<Array<string>> | Yes| Callback used to return task ID matches.| 4725 4726**Error codes** 4727For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4728 4729| ID| Error Message| 4730| -------- | -------- | 4731| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4732| 13400003 | task service ability error. | 4733 4734**Example** 4735 4736 ```ts 4737 import { BusinessError } from '@kit.BasicServicesKit'; 4738 4739 request.agent.search((err: BusinessError, data: Array<string>) => { 4740 if (err) { 4741 console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); 4742 return; 4743 } 4744 console.info(`Upload task search succeeded. `); 4745 }); 4746 ``` 4747 4748## request.agent.search<sup>10+</sup> 4749 4750search(filter: Filter, callback: AsyncCallback<Array<string>>): void 4751 4752Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. 4753 4754**System capability**: SystemCapability.Request.FileTransferAgent 4755 4756**Parameters** 4757 4758| Name| Type| Mandatory| Description| 4759| -------- | -------- | -------- | -------- | 4760| filter | [Filter](#filter10) | Yes| Filter criteria.| 4761| callback | AsyncCallback<Array<string>> | Yes| Callback used to return task ID matches.| 4762 4763**Error codes** 4764For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4765 4766| ID| Error Message| 4767| -------- | -------- | 4768| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4769| 13400003 | task service ability error. | 4770 4771**Example** 4772 4773 ```ts 4774 import { BusinessError } from '@kit.BasicServicesKit'; 4775 4776 let filter: request.agent.Filter = { 4777 action: request.agent.Action.UPLOAD, 4778 mode: request.agent.Mode.BACKGROUND 4779 } 4780 request.agent.search(filter, (err: BusinessError, data: Array<string>) => { 4781 if (err) { 4782 console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); 4783 return; 4784 } 4785 console.info(`Upload task search succeeded. `); 4786 }); 4787 ``` 4788 4789 4790## request.agent.search<sup>10+</sup> 4791 4792search(filter?: Filter): Promise<Array<string>> 4793 4794Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. 4795 4796**System capability**: SystemCapability.Request.FileTransferAgent 4797 4798**Parameters** 4799 4800| Name| Type| Mandatory| Description| 4801| -------- | -------- | -------- | -------- | 4802| filter | [Filter](#filter10) | No| Filter criteria.| 4803 4804**Return value** 4805 4806| Type | Description | 4807| ------------------- | ------------------------- | 4808| Promise<Array<string>> | Promise Promise used to return task ID matches.| 4809 4810**Error codes** 4811For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). 4812 4813| ID| Error Message| 4814| -------- | -------- | 4815| 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed | 4816| 13400003 | task service ability error. | 4817 4818**Example** 4819 4820 ```ts 4821 import { BusinessError } from '@kit.BasicServicesKit'; 4822 4823 let filter: request.agent.Filter = { 4824 action: request.agent.Action.UPLOAD, 4825 mode: request.agent.Mode.BACKGROUND 4826 } 4827 request.agent.search(filter).then((data: Array<string>) => { 4828 console.info(`Upload task search succeeded. `); 4829 }).catch((err: BusinessError) => { 4830 console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); 4831 }); 4832 ``` 4833