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