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