1# @ohos.request (上传下载)
2
3request部件主要给应用提供上传下载文件、后台传输代理的基础能力。
4
5> **说明:**
6>
7> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8
9
10## 导入模块
11
12
13```js
14import { request } from '@kit.BasicServicesKit';
15```
16
17## 常量
18
19**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download20
21### 网络类型
22下载支持自定义网络类型,可以在[DownloadConfig](#downloadconfig)中通过networkType配置成以下网络类型。
23
24| 名称 | 参数类型 | 数值 | 说明 |
25| -------- | -------- | -------- | -------- |
26| NETWORK_MOBILE | number | 0x00000001 | 使用蜂窝网络时允许下载的位标志。 |
27| NETWORK_WIFI | number | 0x00010000 | 使用WLAN时允许下载的位标志。 |
28
29### 下载任务的错误码
30下载[on('fail')<sup>7+</sup>](#onfail7)事件callback的错误参数、[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的failedReason字段取值。
31
32| 名称 | 参数类型 | 数值 | 说明 |
33| -------- | -------- | -------- | -------- |
34| ERROR_CANNOT_RESUME<sup>7+</sup> | number |   0   | 网络原因导致恢复下载失败。 |
35| ERROR_DEVICE_NOT_FOUND<sup>7+</sup> | number |   1   | 找不到SD卡等存储设备。 |
36| ERROR_FILE_ALREADY_EXISTS<sup>7+</sup> | number |   2   | 要下载的文件已存在,下载会话不能覆盖现有文件。 |
37| ERROR_FILE_ERROR<sup>7+</sup> | number |   3   | 文件操作失败。 |
38| ERROR_HTTP_DATA_ERROR<sup>7+</sup> | number |   4   | HTTP传输失败。 |
39| ERROR_INSUFFICIENT_SPACE<sup>7+</sup> | number |   5   | 存储空间不足。 |
40| ERROR_TOO_MANY_REDIRECTS<sup>7+</sup> | number |   6   | 网络重定向过多导致的错误。 |
41| ERROR_UNHANDLED_HTTP_CODE<sup>7+</sup> | number |   7   | 无法识别的HTTP代码。 |
42| ERROR_UNKNOWN<sup>7+</sup> | number |   8   | 未知错误。(例如API version 12及以下版本,只支持串行的尝试连接域名相关ip,且不支持单个ip的连接时间控制,如果DNS返回的首个ip是阻塞的,可能握手超时造成ERROR_UNKNOWN错误。) |
43| ERROR_OFFLINE<sup>9+</sup> | number |   9   | 网络未连接。 |
44| ERROR_UNSUPPORTED_NETWORK_TYPE<sup>9+</sup> | number |   10   | 网络类型不匹配。 |
45
46### 下载任务暂停原因
47下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的pausedReason字段取值。
48
49| 名称 | 参数类型 | 数值 | 说明 |
50| -------- | -------- | -------- | -------- |
51| PAUSED_QUEUED_FOR_WIFI<sup>7+</sup> | number |   0   | 下载被暂停并等待WLAN连接,因为文件大小超过了使用蜂窝网络的会话允许的最大值。 |
52| PAUSED_WAITING_FOR_NETWORK<sup>7+</sup> | number |   1   | 由于网络问题(例如网络断开)而暂停下载。 |
53| PAUSED_WAITING_TO_RETRY<sup>7+</sup> | number |   2   | 发生网络错误,将重试下载会话。 |
54| PAUSED_BY_USER<sup>9+</sup> | number |   3   | 用户暂停会话。 |
55| PAUSED_UNKNOWN<sup>7+</sup> | number |   4   | 未知原因导致暂停下载。 |
56
57### 下载任务状态码
58下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的status字段取值。
59
60| 名称 | 参数类型 | 数值 | 说明 |
61| -------- | -------- | -------- | -------- |
62| SESSION_SUCCESSFUL<sup>7+</sup> | number |   0   | 下载会话已完成。 |
63| SESSION_RUNNING<sup>7+</sup> | number |   1   | 下载会话正在进行中。 |
64| SESSION_PENDING<sup>7+</sup> | number |   2   | 正在调度下载会话。 |
65| SESSION_PAUSED<sup>7+</sup> | number |   3   | 下载会话已暂停。 |
66| SESSION_FAILED<sup>7+</sup> | number |   4   | 下载会话已失败,将不会重试。 |
67
68
69## request.uploadFile<sup>9+</sup>
70
71uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
72
73上传,异步方法,使用promise形式返回结果。通过[on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9)可获取任务上传时的错误信息。
74
75**需要权限**:ohos.permission.INTERNET
76
77**系统能力**:SystemCapability.MiscServices.Upload
78
79**参数:**
80
81  | 参数名 | 类型 | 必填 | 说明 |
82  | -------- | -------- | -------- | -------- |
83  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
84  | config | [UploadConfig](#uploadconfig6) | 是 | 上传的配置信息。 |
85
86
87**返回值:**
88
89  | 类型 | 说明 |
90  | -------- | -------- |
91  | Promise&lt;[UploadTask](#uploadtask)&gt; | 使用Promise方式,异步返回上传任务UploadTask的Promise对象。 |
92
93**错误码:**
94
95以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
96
97  | 错误码ID | 错误信息 |
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**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
128>
129> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
130
131
132## request.uploadFile<sup>9+</sup>
133
134uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
135
136上传,异步方法,使用callback形式返回结果。通过[on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9)可获取任务上传时的错误信息。
137
138**需要权限**:ohos.permission.INTERNET
139
140**系统能力**:SystemCapability.MiscServices.Upload
141
142**参数:**
143
144  | 参数名 | 类型 | 必填 | 说明 |
145  | -------- | -------- | -------- | -------- |
146  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
147  | config | [UploadConfig](#uploadconfig6) | 是 | 上传的配置信息。 |
148  | callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | 是 | 回调函数,异步返回UploadTask对象。当上传成功,err为undefined,data为获取到的UploadTask对象;否则为错误对象。 |
149
150**错误码:**
151
152以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
153
154  | 错误码ID | 错误信息 |
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**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
187>
188> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
189
190## request.upload<sup>(deprecated)</sup>
191
192upload(config: UploadConfig): Promise&lt;UploadTask&gt;
193
194上传,异步方法,使用promise形式返回结果。
195
196**模型约束**:此接口仅可在FA模型下使用
197
198> **说明:**
199>
200> 从API Version 9开始不再维护,建议使用[request.uploadFile<sup>9+</sup>](#requestuploadfile9)替代。
201
202**需要权限**:ohos.permission.INTERNET
203
204**系统能力**:SystemCapability.MiscServices.Upload
205
206**参数:**
207
208  | 参数名 | 类型 | 必填 | 说明 |
209  | -------- | -------- | -------- | -------- |
210  | config | [UploadConfig](#uploadconfig6) | 是 | 上传的配置信息。 |
211
212**返回值:**
213
214  | 类型 | 说明 |
215  | -------- | -------- |
216  | Promise&lt;[UploadTask](#uploadtask)&gt; | 使用Promise方式,异步返回上传任务UploadTask的Promise对象。 |
217
218**错误码:**
219
220以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
221
222  | 错误码ID | 错误信息 |
223  | -------- | -------- |
224  | 201 | the permissions check fails |
225
226**示例:**
227
228  ```js
229  let uploadTask;
230  let uploadConfig = {
231    url: 'http://www.example.com', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
249上传,异步方法,使用callback形式返回结果。
250
251**模型约束**:此接口仅可在FA模型下使用
252
253> **说明:**
254>
255> 从API Version 9开始不再维护,建议使用[request.uploadFile<sup>9+</sup>](#requestuploadfile9-1)替代。
256
257**需要权限**:ohos.permission.INTERNET
258
259**系统能力**:SystemCapability.MiscServices.Upload
260
261**参数:**
262
263  | 参数名 | 类型 | 必填 | 说明 |
264  | -------- | -------- | -------- | -------- |
265  | config | [UploadConfig](#uploadconfig6) | 是 | 上传的配置信息。 |
266  | callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | 是 | 回调函数,异步返回UploadTask对象。当上传成功,err为undefined,data为获取到的UploadTask对象;否则为错误对象。 |
267
268**错误码:**
269
270以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
271
272  | 错误码ID | 错误信息 |
273  | -------- | -------- |
274  | 201 | the permissions check fails |
275
276**示例:**
277
278  ```js
279  let uploadTask;
280  let uploadConfig = {
281    url: 'http://www.example.com', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
298上传任务,使用下列方法前,需要先获取UploadTask对象,promise形式通过[request.uploadFile<sup>9+</sup>](#requestuploadfile9)获取,callback形式通过[request.uploadFile<sup>9+</sup>](#requestuploadfile9-1)获取。
299
300
301
302### on('progress')
303
304on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; void): void
305
306订阅上传任务进度事件,异步方法,使用callback形式返回结果。
307
308> **说明:**
309>
310> 当应用处于后台时,为满足功耗性能要求,不支持调用此接口进行回调。
311
312**系统能力**:SystemCapability.MiscServices.Upload
313
314**参数:**
315
316  | 参数名 | 类型 | 必填 | 说明 |
317  | -------- | -------- | -------- | -------- |
318  | type | string | 是 | 订阅的事件类型,取值为'progress'(上传任务的进度信息)。 |
319  | callback | function | 是 | 上传任务进度的回调函数,返回已上传文件大小和上传文件总大小。 |
320
321  回调函数的参数
322
323| 参数名 | 类型 | 必填 | 说明 |
324| -------- | -------- | -------- | -------- |
325| uploadedSize | number | 是 | 当前已上传文件大小,单位为字节。 |
326| totalSize | number | 是 | 上传文件的总大小,单位为字节。 |
327
328**错误码:**
329
330以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
331
332  | 错误码ID | 错误信息 |
333  | -------- | -------- |
334  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
335
336**示例:**
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
351订阅上传任务HTTP响应事件,异步方法,使用callback形式返回结果。
352
353**系统能力**: SystemCapability.MiscServices.Upload
354
355**参数:**
356
357  | 参数名 | 类型 | 必填 | 说明 |
358  | -------- | -------- | -------- | -------- |
359  | type | string | 是 | 订阅的事件类型,取值为'headerReceive'(接收响应)。 |
360  | callback | function | 是 | HTTP&nbsp;Response事件的回调函数,返回响应请求内容。 |
361
362  回调函数的参数:
363
364| 参数名 | 类型 | 必填 | 说明 |
365| -------- | -------- | -------- | -------- |
366| header | object | 是 | HTTP&nbsp;Response。 |
367
368**错误码:**
369
370以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
371
372  | 错误码ID | 错误信息 |
373  | -------- | -------- |
374  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
375
376**示例:**
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
391订阅上传任务完成或失败事件,异步方法,使用callback形式返回结果。
392
393**系统能力**:SystemCapability.MiscServices.Upload
394
395**参数:**
396
397  | 参数名 | 类型 | 必填 | 说明 |
398  | -------- | -------- | -------- | -------- |
399  | type | string | 是 | 订阅上传任务的回调类型,支持的事件包括:`'complete'`\|`'fail'`。<br/>\-`'complete'`:表示上传任务完成。 <br/>\-`'fail'`:表示上传任务失败。 
400  | callback | Callback&lt;Array&lt;[TaskState](#taskstate9)&gt;&gt; | 是 | 上传任务完成或失败的回调函数。返回上传任务的任务状态信息。 |
401
402
403**错误码:**
404
405以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
406
407  | 错误码ID | 错误信息 |
408  | -------- | -------- |
409  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
410
411**示例:**
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
435取消订阅上传任务进度事件。
436
437**系统能力**:SystemCapability.MiscServices.Upload
438
439**参数:**
440
441  | 参数名 | 类型 | 必填 | 说明 |
442  | -------- | -------- | -------- | -------- |
443  | type | string | 是 | 取消订阅的事件类型,取值为'progress'(上传的进度信息)。 |
444  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
445
446回调函数的参数
447
448| 参数名 | 类型 | 必填 | 说明 |
449| -------- | -------- | -------- | -------- |
450| uploadedSize | number | 是 | 当前已上传文件大小,单位为字节。 |
451| totalSize | number | 是 | 上传文件的总大小,单位为字节。 |
452**错误码:**
453
454以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
455
456  | 错误码ID | 错误信息 |
457  | -------- | -------- |
458  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
459
460**示例:**
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  //表示取消upProgressCallback1的订阅
473  uploadTask.off('progress', upProgressCallback1);
474  //表示取消订阅上传任务进度事件的所有回调
475  uploadTask.off('progress');
476  ```
477
478
479### off('headerReceive')<sup>7+</sup>
480
481off(type: 'headerReceive', callback?: (header: object) =&gt; void): void
482
483取消订阅上传任务HTTP响应事件。
484
485**系统能力**:SystemCapability.MiscServices.Upload
486
487**参数:**
488
489  | 参数名 | 类型 | 必填 | 说明 |
490  | -------- | -------- | -------- | -------- |
491  | type | string | 是 | 取消订阅的事件类型,取值为'headerReceive'(接收响应)。 |
492  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
493
494**错误码:**
495
496以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
497
498  | 错误码ID | 错误信息 |
499  | -------- | -------- |
500  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
501
502**示例:**
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  //表示取消headerCallback1的订阅
515  uploadTask.off('headerReceive', headerCallback1);
516  //表示取消订阅上传任务HTTP标头事件的所有回调
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
524取消订阅上传任务完成或失败事件。
525
526**系统能力**:SystemCapability.MiscServices.Upload
527
528**参数:**
529
530  | 参数名 | 类型 | 必填 | 说明 |
531  | -------- | -------- | -------- | -------- |
532  | type | string | 是 | 订阅的事件类型,取值为'complete',表示上传任务完成;取值为'fail',表示上传任务失败。|
533  | callback | Callback&lt;Array&lt;[TaskState](#taskstate9)&gt;&gt; | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
534
535**错误码:**
536
537以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
538
539  | 错误码ID | 错误信息 |
540  | -------- | -------- |
541  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
542
543**示例:**
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  //表示取消headerCallback1的订阅
562  uploadTask.off('complete', upCompleteCallback1);
563  //表示取消订阅上传任务完成的所有回调
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  //表示取消headerCallback1的订阅
581  uploadTask.off('fail', upFailCallback1);
582  //表示取消订阅上传任务失败的所有回调
583  uploadTask.off('fail');
584  ```
585
586### delete<sup>9+</sup>
587delete(): Promise&lt;boolean&gt;
588
589移除上传的任务,异步方法,使用promise形式返回结果。
590
591**需要权限**:ohos.permission.INTERNET
592
593**系统能力**:SystemCapability.MiscServices.Upload
594
595**返回值:**
596
597  | 类型 | 说明 |
598  | -------- | -------- |
599  | Promise&lt;boolean&gt; | 使用Promise方式异步回调,返回true表示移除上传任务成功;返回false表示移除上传任务失败。 |
600
601**错误码:**
602
603以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
604
605  | 错误码ID | 错误信息 |
606  | -------- | -------- |
607  | 201 | the permissions check fails |
608
609**示例:**
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> **说明:**
621>
622> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
623
624
625### delete<sup>9+</sup>
626
627delete(callback: AsyncCallback&lt;boolean&gt;): void
628
629移除上传的任务,异步方法,使用callback形式返回结果。
630
631**需要权限**:ohos.permission.INTERNET
632
633**系统能力**:SystemCapability.MiscServices.Upload
634
635**参数:**
636
637  | 参数名 | 类型 | 必填 | 说明 |
638  | -------- | -------- | -------- | -------- |
639  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示异步返回移除任务成功;返回false表示异步返回移除任务失败。 |
640
641**错误码:**
642
643以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
644
645  | 错误码ID | 错误信息 |
646  | -------- | -------- |
647  | 201 | the permissions check fails |
648
649**示例:**
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> **说明:**
663>
664> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
665
666
667### remove<sup>(deprecated)</sup>
668
669remove(): Promise&lt;boolean&gt;
670
671移除上传的任务,异步方法,使用promise形式返回结果。
672
673> **说明:**
674>
675> 从API Version 9开始不再维护,建议使用[delete<sup>9+</sup>](#delete9)替代。
676
677**需要权限**:ohos.permission.INTERNET
678
679**系统能力**:SystemCapability.MiscServices.Upload
680
681**返回值:**
682
683  | 类型 | 说明 |
684  | -------- | -------- |
685  | Promise&lt;boolean&gt; | 使用Promise方式异步回调,返回true表示移除上传任务成功;返回false表示移除上传任务失败。 |
686
687**错误码:**
688
689以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
690
691  | 错误码ID | 错误信息 |
692  | -------- | -------- |
693  | 201 | the permissions check fails |
694
695**示例:**
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
710移除上传的任务,异步方法,使用callback形式返回结果。
711
712> **说明:**
713>
714> 从API Version 9开始不再维护,建议使用[delete<sup>9+</sup>](#delete9-1)替代。
715
716**需要权限**:ohos.permission.INTERNET
717
718**系统能力**:SystemCapability.MiscServices.Upload
719
720**参数:**
721
722  | 参数名 | 类型 | 必填 | 说明 |
723  | -------- | -------- | -------- | -------- |
724  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示异步返回移除任务成功;返回false表示异步返回移除任务失败。 |
725
726**错误码:**
727
728以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
729
730  | 错误码ID | 错误信息 |
731  | -------- | -------- |
732  | 201 | the permissions check fails |
733
734**示例:**
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>
751上传任务的配置信息。
752
753**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.Upload754
755| 名称 | 类型 | 必填 | 说明 |
756| -------- | -------- | -------- | -------- |
757| url | string | 是 | 资源地址,其最大长度为2048个字符。 |
758| header | Object | 是 | 添加要包含在上传请求中的HTTP或HTTPS标志头。 |
759| method | string | 是 |  HTTP请求方法:POST、PUT,缺省为POST。使用PUT修改资源,使用POST新增资源。 |
760| index<sup>11+</sup> | number | 否 | 任务的路径索引,默认值为0。 |
761| begins<sup>11+</sup> | number | 否 | 在上传开始时读取的文件起点。默认值为0,取值为闭区间。|
762| ends<sup>11+</sup> | number | 否 | 在上传结束时读取的文件终点。默认值为-1,取值为闭区间。 |
763| files | Array&lt;[File](#file)&gt; | 是 | 要上传的文件列表。文件以 HTTP 的 multipart/form-data 格式提交。 |
764| data | Array&lt;[RequestData](#requestdata)&gt; | 是 | 请求的表单数据。 |
765
766## TaskState<sup>9+</sup>
767上传任务的任务信息,是[on('complete' | 'fail')<sup>9+</sup>](#oncomplete--fail9)和[off('complete' | 'fail')<sup>9+</sup>](#offcomplete--fail9)接口的回调参数。
768
769**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload770
771| 名称 | 类型 | 必填 | 说明                                                                                                                                        |
772| -------- | -------- | -------- |-------------------------------------------------------------------------------------------------------------------------------------------|
773| path | string | 是 | 文件路径                                                                                                                                      |
774| responseCode | number | 是 | 上传任务返回值,0表示任务成功,其它返回码为失败,具体请查看message上传任务结果描述信息。此处推荐使用[request.agent.create<sup>10+</sup>](#requestagentcreate10-1)创建上传任务,并获取标准错误码处理异常分支。 |
775| message | string | 是 | 上传任务结果描述信息                                                                                                                                |
776
777其中,responseCode包含的返回码值如下:
778
779| 返回码 | 具体信息                               |
780|-----|------------------------------------|
781| 0   | 上传成功                               |
782| 5   | 任务被主动暂停或停止                         |
783| 6   | 任务所属应用被切换到后台或终止,导致前台任务被停止,请检查应用状态  |
784| 7   | 无网络,请检查设备是否处于联网状态                  |
785| 8   | 网络类型不匹配,请检查当前网络类型和任务所需网络类型是否匹配     |
786| 10  | 创建HTTP请求失败,请检查参数是否正确或重试任务          |
787| 12  | 超时,请检查参数是否正确、检查网络,又或是重试任务          |
788| 13  | 连接失败,请检查参数是否正确、检查网络,又或是重试任务        |
789| 14  | 请求失败,请检查参数是否正确、检查网络,又或是重试任务        |
790| 15  | 上传失败,请检查参数是否正确、检查网络,又或是重试任务        |
791| 16  | 重定向失败,请检查参数是否正确、检查网络,又或是重试任务       |
792| 17  | 协议错误,服务器返回 4XX 或 5XX 状态码,请检查参数是否正确 |
793| 20  | 其他错误,请检查参数是否正确、检查网络,又或是重试任务        |
794
795## File
796[UploadConfig<sup>6+<sup>](#uploadconfig6)中的文件列表。
797
798**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download799
800| 名称 | 类型 | 必填 | 说明 |
801| -------- | -------- | -------- | -------- |
802| filename | string | 是 | multipart提交时,请求头中的文件名。 |
803| name | string | 是 | multipart提交时,表单项目的名称,缺省为file。 |
804| uri | string | 是 | 文件的本地存储路径。<br/>仅支持"internal"协议类型,仅支持"internal://cache/",即调用方(即传入的context)对应的缓存路径context.cacheDir。<br/>示例:internal://cache/path/to/file.txt |
805| type | string | 是 | 文件的内容类型,默认根据文件名或路径的后缀获取。 |
806
807
808## RequestData
809[UploadConfig<sup>6+<sup>](#uploadconfig6)中的表单数据。
810
811**系统能力**:以下各项对应的系统能力均为SystemCapability.MiscServices.Download812
813| 名称 | 类型 | 必填 | 说明 |
814| -------- | -------- | -------- | -------- |
815| name | string | 是 | 表示表单元素的名称。 |
816| value | string | 是 | 表示表单元素的值。 |
817
818## request.downloadFile<sup>9+</sup>
819
820downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
821
822下载,异步方法,使用promise形式返回结果。通过[on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7)可获取任务下载时的状态信息,包括任务完成、暂停或移除。通过[on('fail')<sup>7+</sup>](#onfail7)可获取任务下载时的错误信息。
823
824**需要权限**:ohos.permission.INTERNET
825
826**系统能力**:SystemCapability.MiscServices.Download
827
828**参数:**
829
830  | 参数名 | 类型 | 必填 | 说明 |
831  | -------- | -------- | -------- | -------- |
832  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
833  | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
834
835**返回值:**
836
837  | 类型 | 说明 |
838  | -------- | -------- |
839  | Promise&lt;[DownloadTask](#downloadtask)&gt; | 使用Promise方式,异步返回下载任务DownloadTask的Promise对象。 |
840
841**错误码:**
842
843以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。。
844
845  | 错误码ID | 错误信息 |
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**示例:**
854
855  ```ts
856import { BusinessError } from '@kit.BasicServicesKit';
857
858  try {
859    // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
871>
872> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
873
874
875## request.downloadFile<sup>9+</sup>
876
877downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
878
879下载,异步方法,使用callback形式返回结果。通过[on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7)可获取任务下载时的状态信息,包括任务完成、暂停或移除。通过[on('fail')<sup>7+</sup>](#onfail7)可获取任务下载时的错误信息。
880
881**需要权限**:ohos.permission.INTERNET
882
883**系统能力**:SystemCapability.MiscServices.Download
884
885**参数:**
886
887  | 参数名 | 类型 | 必填 | 说明 |
888  | -------- | -------- | -------- | -------- |
889  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
890  | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
891  | callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | 是 | 回调函数。当下载任务成功,err为undefined,data为获取到的DownloadTask对象;否则为错误对象。 |
892
893**错误码:**
894
895以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。。
896
897  | 错误码ID | 错误信息 |
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**示例:**
906
907  ```ts
908import { BusinessError } from '@kit.BasicServicesKit';
909
910  try {
911    // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
928>
929> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
930
931## request.download<sup>(deprecated)</sup>
932
933download(config: DownloadConfig): Promise&lt;DownloadTask&gt;
934
935下载,异步方法,使用promise形式返回结果。
936
937> **说明:**
938>
939> 从API Version 9开始不再维护,建议使用[request.downloadFile<sup>9+</sup>](#requestdownloadfile9)替代。
940
941**模型约束**:此接口仅可在FA模型下使用
942
943**需要权限**:ohos.permission.INTERNET
944
945**系统能力**:SystemCapability.MiscServices.Download
946
947**参数:**
948
949  | 参数名 | 类型 | 必填 | 说明 |
950  | -------- | -------- | -------- | -------- |
951  | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
952
953**返回值:**
954
955  | 类型 | 说明 |
956  | -------- | -------- |
957  | Promise&lt;[DownloadTask](#downloadtask)&gt; | 使用Promise方式,异步返回下载任务DownloadTask的Promise对象。 |
958
959**错误码:**
960
961以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
962
963  | 错误码ID | 错误信息 |
964  | -------- | -------- |
965  | 201 | the permissions check fails |
966
967**示例:**
968
969  ```js
970  let downloadTask;
971  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
984下载,异步方法,使用callback形式返回结果。
985
986> **说明:**
987>
988> 从API Version 9开始不再维护,建议使用[request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1)替代。
989
990**模型约束**:此接口仅可在FA模型下使用
991
992**需要权限**:ohos.permission.INTERNET
993
994**系统能力**:SystemCapability.MiscServices.Download
995
996**参数:**
997
998  | 参数名 | 类型 | 必填 | 说明 |
999  | -------- | -------- | -------- | -------- |
1000  | config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 |
1001  | callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | 是 | 回调函数。当下载任务成功,err为undefined,data为获取到的DownloadTask对象;否则为错误对象。 |
1002
1003**错误码:**
1004
1005以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
1006
1007| 错误码ID | 错误信息 |
1008  | -------- | -------- |
1009| 201 | the permissions check fails |
1010
1011**示例:**
1012
1013  ```js
1014  let downloadTask;
1015  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
1028下载任务,使用下列方法前,需要先获取DownloadTask对象,promise形式通过[request.downloadFile<sup>9+</sup>](#requestdownloadfile9)获取,callback形式通过[request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1)获取。
1029
1030
1031### on('progress')
1032
1033on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; void): void
1034
1035订阅下载任务进度事件,异步方法,使用callback形式返回结果。
1036
1037> **说明:**
1038>
1039> 当应用处于后台时,为满足功耗性能要求,不支持调用此接口进行回调。
1040
1041**系统能力**:SystemCapability.MiscServices.Download
1042
1043**参数:**
1044
1045  | 参数名 | 类型 | 必填 | 说明 |
1046  | -------- | -------- | -------- | -------- |
1047  | type | string | 是 | 订阅的事件类型,取值为'progress'(下载的进度信息)。 |
1048  | callback | function | 是 | 下载任务进度的回调函数,返回已上传文件大小和上传文件总大小。 |
1049
1050  回调函数的参数:
1051
1052| 参数名 | 类型 | 必填 | 说明                                                                      |
1053| -------- | -------- | -------- |-------------------------------------------------------------------------|
1054| receivedSize | number | 是 | 当前下载的进度,单位为字节。                                                           |
1055| totalSize | number | 是 | 下载文件的总大小,单位为字节。在下载过程中,若服务器使用 chunk 方式传输导致无法从请求头中获取文件总大小时,totalSize 为 -1。 |
1056
1057**错误码:**
1058
1059以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1060
1061  | 错误码ID | 错误信息 |
1062  | -------- | -------- |
1063  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1064
1065**示例:**
1066
1067  ```ts
1068import { BusinessError } from '@kit.BasicServicesKit';
1069
1070  try {
1071    // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
1091取消订阅下载任务进度事件。
1092
1093**系统能力**:SystemCapability.MiscServices.Download
1094
1095**参数:**
1096
1097  | 参数名 | 类型 | 必填 | 说明 |
1098  | -------- | -------- | -------- | -------- |
1099  | type | string | 是 | 取消订阅的事件类型,取值为'progress'(下载的进度信息)。 |
1100  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
1101  
1102  回调函数的参数:
1103
1104| 参数名 | 类型 | 必填 | 说明                                                                      |
1105| -------- | -------- | -------- |-------------------------------------------------------------------------|
1106| receivedSize | number | 是 | 当前下载的进度,单位为字节。                                                           |
1107| totalSize | number | 是 | 下载文件的总大小,单位为字节。在下载过程中,若服务器使用 chunk 方式传输导致无法从请求头中获取文件总大小时,totalSize 为 -1。 |
1108
1109**错误码:**
1110
1111以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1112
1113  | 错误码ID | 错误信息 |
1114  | -------- | -------- |
1115  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1116
1117**示例:**
1118
1119  ```ts
1120import { BusinessError } from '@kit.BasicServicesKit';
1121
1122try {
1123  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消progressCallback1的订阅
1135    downloadTask.off('progress', progressCallback1);
1136    //表示取消订阅下载任务进度事件的所有回调
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
1151订阅下载任务相关的事件,异步方法,使用callback形式返回。
1152
1153**系统能力**: SystemCapability.MiscServices.Download
1154
1155**参数:**
1156
1157  | 参数名 | 类型 | 必填 | 说明 |
1158  | -------- | -------- | -------- | -------- |
1159  | type | string | 是 | 订阅的事件类型。<br>- 取值为'complete',表示下载任务完成;<br/>- 取值为'pause',表示下载任务暂停;<br/>- 取值为'remove',表示下载任务移除。 |
1160  | callback | function | 是 | 下载任务相关的回调函数。|
1161
1162**错误码:**
1163
1164以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1165
1166  | 错误码ID | 错误信息 |
1167  | -------- | -------- |
1168  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1169
1170**示例:**
1171
1172  ```ts
1173import { BusinessError } from '@kit.BasicServicesKit';
1174
1175try {
1176  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
1206取消订阅下载任务相关的事件。
1207
1208**系统能力**:SystemCapability.MiscServices.Download
1209
1210**参数:**
1211
1212  | 参数名 | 类型 | 必填 | 说明 |
1213  | -------- | -------- | -------- | -------- |
1214  | type | string | 是 | 取消订阅的事件类型。<br/>- 取值为'complete',表示下载任务完成;<br/>- 取值为'pause',表示下载任务暂停;<br/>- 取值为'remove',表示下载任务移除。 |
1215  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
1216
1217**错误码:**
1218
1219以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1220
1221  | 错误码ID | 错误信息 |
1222  | -------- | -------- |
1223  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1224
1225**示例:**
1226
1227  ```ts
1228import { BusinessError } from '@kit.BasicServicesKit';
1229
1230try {
1231  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消completeCallback1的订阅
1243    downloadTask.off('complete', completeCallback1);
1244    //表示取消订阅下载任务完成的所有回调
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    //表示取消pauseCallback1的订阅
1256    downloadTask.off('pause', pauseCallback1);
1257    //表示取消订阅下载任务暂停的所有回调
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    //表示取消removeCallback1的订阅
1269    downloadTask.off('remove', removeCallback1);
1270    //表示取消订阅下载任务移除的所有回调
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
1286订阅下载任务失败事件,异步方法,使用callback形式返回结果。
1287
1288**系统能力**:SystemCapability.MiscServices.Download
1289
1290**参数:**
1291
1292  | 参数名 | 类型 | 必填 | 说明 |
1293  | -------- | -------- | -------- | -------- |
1294  | type | string | 是 | 订阅的事件类型,取值为'fail'(下载失败)。 |
1295  | callback | function | 是 | 下载失败的回调函数。 |
1296
1297  回调函数的参数:
1298
1299| 参数名 | 类型 | 必填 | 说明 |
1300| -------- | -------- | -------- | -------- |
1301| err | number | 是 | 下载失败的错误码,错误原因见[下载任务的错误码](#下载任务的错误码)。 |
1302
1303**错误码:**
1304
1305以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1306
1307  | 错误码ID | 错误信息 |
1308  | -------- | -------- |
1309  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1310
1311**示例:**
1312
1313  ```ts
1314import { BusinessError } from '@kit.BasicServicesKit';
1315
1316try {
1317  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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
1337取消订阅下载任务失败事件。
1338
1339**系统能力**:SystemCapability.MiscServices.Download
1340
1341**参数:**
1342
1343  | 参数名 | 类型 | 必填 | 说明 |
1344  | -------- | -------- | -------- | -------- |
1345  | type | string | 是 | 取消订阅的事件类型,取值为'fail'(下载失败)。 |
1346  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
1347
1348**错误码:**
1349
1350以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1351
1352  | 错误码ID | 错误信息 |
1353  | -------- | -------- |
1354  | 401 | the parameters check fails.Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
1355
1356**示例:**
1357
1358  ```ts
1359import { BusinessError } from '@kit.BasicServicesKit';
1360
1361try {
1362  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消failCallback1的订阅
1374    downloadTask.off('fail', failCallback1);
1375    //表示取消订阅下载任务失败的所有回调
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
1389移除下载的任务,异步方法,使用promise形式返回结果。
1390
1391**需要权限**:ohos.permission.INTERNET
1392
1393**系统能力**:SystemCapability.MiscServices.Download
1394
1395**返回值:**
1396
1397  | 类型 | 说明 |
1398  | -------- | -------- |
1399  | Promise&lt;boolean&gt; | 使用promise方式异步回调,返回true表示移除下载任务成功;返回false表示移除下载任务失败。 |
1400
1401**错误码:**
1402
1403以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1404
1405  | 错误码ID | 错误信息 |
1406  | -------- | -------- |
1407  | 201 | the permissions check fails |
1408
1409**示例:**
1410
1411  ```ts
1412import { BusinessError } from '@kit.BasicServicesKit';
1413
1414try {
1415  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1432>
1433> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1434
1435
1436### delete<sup>9+</sup>
1437
1438delete(callback: AsyncCallback&lt;boolean&gt;): void
1439
1440移除下载的任务,异步方法,使用callback形式返回结果。
1441
1442**需要权限**:ohos.permission.INTERNET
1443
1444**系统能力**:SystemCapability.MiscServices.Download
1445
1446**参数:**
1447
1448  | 参数名 | 类型 | 必填 | 说明 |
1449  | -------- | -------- | -------- | -------- |
1450  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示异步返回移除任务是否成功;返回false表示异步返回移除任务失败。 |
1451
1452**错误码:**
1453
1454以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1455
1456  | 错误码ID | 错误信息 |
1457  | -------- | -------- |
1458  | 201 | the permissions check fails |
1459
1460**示例:**
1461
1462  ```ts
1463import { BusinessError } from '@kit.BasicServicesKit';
1464
1465try {
1466  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1485>
1486> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1487
1488
1489### getTaskInfo<sup>9+</sup>
1490
1491getTaskInfo(): Promise&lt;DownloadInfo&gt;
1492
1493查询下载任务的信息,异步方法,使用promise形式返回DownloadInfo里的信息。
1494
1495**需要权限**:ohos.permission.INTERNET
1496
1497**系统能力**:SystemCapability.MiscServices.Download
1498
1499**返回值:**
1500
1501  | 类型 | 说明 |
1502  | -------- | -------- |
1503  | Promise&lt;[DownloadInfo](#downloadinfo7)&gt; |  使用promise方式,异步返回下载任务信息DownloadInfo的Promise对象。 |
1504
1505**错误码:**
1506
1507以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1508
1509  | 错误码ID | 错误信息 |
1510  | -------- | -------- |
1511  | 201 | the permissions check fails |
1512
1513**示例:**
1514
1515  ```ts
1516import { BusinessError } from '@kit.BasicServicesKit';
1517
1518try {
1519  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1536>
1537> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1538
1539
1540### getTaskInfo<sup>9+</sup>
1541
1542getTaskInfo(callback: AsyncCallback&lt;DownloadInfo&gt;): void
1543
1544查询下载的任务,异步方法,使用callback形式返回结果。
1545
1546**需要权限**:ohos.permission.INTERNET
1547
1548**系统能力**:SystemCapability.MiscServices.Download
1549
1550**参数:**
1551
1552  | 参数名 | 类型 | 必填 | 说明 |
1553  | -------- | -------- | -------- | -------- |
1554  | callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | 是 | 回调函数。当查询下载任务操作成功,err为undefined,data为获取到的DownloadInfo对象;否则为错误对象。 |
1555
1556**错误码:**
1557
1558以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1559
1560  | 错误码ID | 错误信息 |
1561  | -------- | -------- |
1562  | 201 | the permissions check fails |
1563
1564**示例:**
1565
1566  ```ts
1567import { BusinessError } from '@kit.BasicServicesKit';
1568
1569try {
1570  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1589>
1590> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1591
1592
1593### getTaskMimeType<sup>9+</sup>
1594
1595getTaskMimeType(): Promise&lt;string&gt;
1596
1597查询下载的任务的MimeType(HTTP中表示资源的媒体类型),异步方法,使用promise形式返回结果。
1598
1599**需要权限**:ohos.permission.INTERNET
1600
1601**系统能力**:SystemCapability.MiscServices.Download
1602
1603**返回值:**
1604
1605  | 类型 | 说明 |
1606  | -------- | -------- |
1607  | Promise&lt;string&gt; | 使用promise方式,异步返回下载任务的MimeType的Promise对象。 |
1608
1609**错误码:**
1610
1611以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1612
1613  | 错误码ID | 错误信息 |
1614  | -------- | -------- |
1615  | 201 | the permissions check fails |
1616
1617**示例:**
1618
1619  ```ts
1620import { BusinessError } from '@kit.BasicServicesKit';
1621
1622try {
1623  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1640>
1641> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1642
1643
1644### getTaskMimeType<sup>9+</sup>
1645
1646getTaskMimeType(callback: AsyncCallback&lt;string&gt;): void;
1647
1648查询下载的任务的 MimeType,异步方法,使用callback形式返回结果。
1649
1650**需要权限**:ohos.permission.INTERNET
1651
1652**系统能力**:SystemCapability.MiscServices.Download
1653
1654**参数:**
1655
1656  | 参数名 | 类型 | 必填 | 说明 |
1657  | -------- | -------- | -------- | -------- |
1658  | callback | AsyncCallback&lt;string&gt; | 是 | 回调函数。当查询下载任务MimeType成功,err为undefined,data为获取到的下载任务的MimeType对象;否则为错误对象。 |
1659
1660**错误码:**
1661
1662以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1663
1664  | 错误码ID | 错误信息 |
1665  | -------- | -------- |
1666  | 201 | the permissions check fails |
1667
1668**示例:**
1669
1670  ```ts
1671import { BusinessError } from '@kit.BasicServicesKit';
1672
1673try {
1674  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1693>
1694> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1695
1696
1697### suspend<sup>9+</sup>
1698
1699suspend(): Promise&lt;boolean&gt;
1700
1701暂停下载任务,异步方法,使用promise形式返回结果。
1702
1703**需要权限**:ohos.permission.INTERNET
1704
1705**系统能力**:SystemCapability.MiscServices.Download
1706
1707**返回值:**
1708
1709  | 类型 | 说明 |
1710  | -------- | -------- |
1711  | Promise&lt;boolean&gt; | 使用promise方式异步回调,返回true表示暂停下载任务成功;返回false表示暂停下载任务失败。 |
1712
1713**错误码:**
1714
1715以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1716
1717  | 错误码ID | 错误信息 |
1718  | -------- | -------- |
1719  | 201 | the permissions check fails |
1720
1721**示例:**
1722
1723  ```ts
1724import { BusinessError } from '@kit.BasicServicesKit';
1725
1726try {
1727  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1744>
1745> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1746
1747
1748### suspend<sup>9+</sup>
1749
1750suspend(callback: AsyncCallback&lt;boolean&gt;): void
1751
1752暂停下载任务,异步方法,使用callback形式返回结果。
1753
1754**需要权限**:ohos.permission.INTERNET
1755
1756**系统能力**:SystemCapability.MiscServices.Download
1757
1758**参数:**
1759
1760  | 参数名 | 类型 | 必填 | 说明 |
1761  | -------- | -------- | -------- | -------- |
1762  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示暂停下载任务成功;返回false表示暂停下载任务失败。 |
1763
1764**错误码:**
1765
1766以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1767
1768  | 错误码ID | 错误信息 |
1769  | -------- | -------- |
1770  | 201 | the permissions check fails |
1771
1772**示例:**
1773
1774  ```ts
1775import { BusinessError } from '@kit.BasicServicesKit';
1776
1777try {
1778  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1797>
1798> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1799
1800
1801### restore<sup>9+</sup>
1802
1803restore(): Promise&lt;boolean&gt;
1804
1805重新启动暂停的下载任务,异步方法,使用promise形式返回结果。
1806
1807**需要权限**:ohos.permission.INTERNET
1808
1809**系统能力**:SystemCapability.MiscServices.Download
1810
1811**返回值:**
1812
1813  | 类型 | 说明 |
1814  | -------- | -------- |
1815  | Promise&lt;boolean&gt; | 使用promise方式异步回调,返回true表示重新启动已暂停的下载任务成功;返回false表示重新启动下载任务失败。 |
1816
1817**错误码:**
1818
1819以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1820
1821  | 错误码ID | 错误信息 |
1822  | -------- | -------- |
1823  | 201 | the permissions check fails |
1824
1825**示例:**
1826
1827  ```ts
1828import { BusinessError } from '@kit.BasicServicesKit';
1829
1830try {
1831  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1848>
1849> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1850
1851
1852### restore<sup>9+</sup>
1853
1854restore(callback: AsyncCallback&lt;boolean&gt;): void
1855
1856重新启动暂停的下载任务,异步方法,使用callback形式返回结果。
1857
1858**需要权限**:ohos.permission.INTERNET
1859
1860**系统能力**:SystemCapability.MiscServices.Download
1861
1862**参数:**
1863
1864  | 参数名 | 类型 | 必填 | 说明 |
1865  | -------- | -------- | -------- | -------- |
1866  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示重新启动已暂停的下载任务成功;返回false表示重新启动下载任务失败。 |
1867
1868**错误码:**
1869
1870以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
1871
1872  | 错误码ID | 错误信息 |
1873  | -------- | -------- |
1874  | 201 | the permissions check fails |
1875
1876**示例:**
1877
1878  ```ts
1879import { BusinessError } from '@kit.BasicServicesKit';
1880
1881try {
1882  // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
1901>
1902> 由于不存在401报错场景,在 api12 中 `401 the parameters check fails` 这个错误码被移除。
1903
1904
1905### remove<sup>(deprecated)</sup>
1906
1907remove(): Promise&lt;boolean&gt;
1908
1909移除下载的任务,异步方法,使用promise形式返回结果。
1910
1911> **说明:**
1912>
1913> 从API Version 9开始不再维护,建议使用[delete<sup>9+</sup>](#delete9-2)替代。
1914
1915**需要权限**:ohos.permission.INTERNET
1916
1917**系统能力**:SystemCapability.MiscServices.Download
1918
1919**返回值:**
1920
1921  | 类型 | 说明 |
1922  | -------- | -------- |
1923  | Promise&lt;boolean&gt; | 使用promise方式异步回调,返回true表示移除下载任务成功;返回false表示移除下载任务失败。 |
1924
1925**错误码:**
1926
1927以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
1928
1929  | 错误码ID | 错误信息 |
1930  | -------- | -------- |
1931  | 201 | the permissions check fails |
1932
1933**示例:**
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
1948移除下载的任务,异步方法,使用callback形式返回结果。
1949
1950> **说明:**
1951>
1952> 从API Version 9开始不再维护,建议使用[delete<sup>9+</sup>](#delete9-3)替代。
1953
1954**需要权限**:ohos.permission.INTERNET
1955
1956**系统能力**:SystemCapability.MiscServices.Download
1957
1958**参数:**
1959
1960  | 参数名 | 类型 | 必填 | 说明 |
1961  | -------- | -------- | -------- | -------- |
1962  | callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。返回true表示移除下载任务成功;返回false表示移除下载任务失败。 |
1963
1964**错误码:**
1965
1966以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
1967
1968  | 错误码ID | 错误信息 |
1969  | -------- | -------- |
1970  | 201 | the permissions check fails |
1971
1972**示例:**
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
1989查询下载任务,异步方法,使用promise形式返回DownloadInfo里的信息。
1990
1991> **说明:**
1992>
1993> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[getTaskInfo<sup>9+</sup>](#gettaskinfo9)替代。
1994
1995**需要权限**:ohos.permission.INTERNET
1996
1997**系统能力**:SystemCapability.MiscServices.Download
1998
1999**返回值:**
2000
2001  | 类型 | 说明 |
2002  | -------- | -------- |
2003  | Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | 使用promise方式,异步返回下载任务信息DownloadInfo的Promise对象。 |
2004
2005**错误码:**
2006
2007以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2008
2009  | 错误码ID | 错误信息 |
2010  | -------- | -------- |
2011  | 201 | the permissions check fails |
2012
2013**示例:**
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
2028查询下载的任务,异步方法,使用callback形式返回结果。
2029
2030> **说明:**
2031>
2032> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[getTaskInfo<sup>9+</sup>](#gettaskinfo9-1)替代。
2033
2034**需要权限**:ohos.permission.INTERNET
2035
2036**系统能力**:SystemCapability.MiscServices.Download
2037
2038**参数:**
2039
2040  | 参数名 | 类型 | 必填 | 说明 |
2041  | -------- | -------- | -------- | -------- |
2042  | callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | 是 | 回调函数。当查询下载任务成功,err为undefined,data为获取到的DownloadInfo对象;否则为错误对象。 |
2043
2044**错误码:**
2045
2046以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2047
2048  | 错误码ID | 错误信息 |
2049  | -------- | -------- |
2050  | 201 | the permissions check fails |
2051
2052**示例:**
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
2069查询下载的任务的MimeType,异步方法,使用promise形式返回结果。
2070
2071> **说明:**
2072>
2073> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[getTaskMimeType<sup>9+</sup>](#gettaskmimetype9)替代。
2074
2075**需要权限**:ohos.permission.INTERNET
2076
2077**系统能力**:SystemCapability.MiscServices.Download
2078
2079**返回值:**
2080
2081  | 类型 | 说明 |
2082  | -------- | -------- |
2083  | Promise&lt;string&gt; | 使用promise方式,异步返回下载任务的MimeType的Promise对象。 |
2084
2085**错误码:**
2086
2087以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2088
2089  | 错误码ID | 错误信息 |
2090  | -------- | -------- |
2091  | 201 | the permissions check fails |
2092
2093**示例:**
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
2108查询下载的任务的MimeType,异步方法,使用callback形式返回结果。
2109
2110> **说明:**
2111>
2112> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[getTaskMimeType<sup>9+</sup>](#gettaskmimetype9-1)替代。
2113
2114**需要权限**:ohos.permission.INTERNET
2115
2116**系统能力**:SystemCapability.MiscServices.Download
2117
2118**参数:**
2119
2120  | 参数名 | 类型 | 必填 | 说明 |
2121  | -------- | -------- | -------- | -------- |
2122  | callback | AsyncCallback&lt;string&gt; | 是 | 回调函数。当查询下载任务的MimeType成功,err为undefined,data为获取到的任务MimeType对象;否则为错误对象。 |
2123
2124**错误码:**
2125
2126以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2127
2128  | 错误码ID | 错误信息 |
2129  | -------- | -------- |
2130  | 201 | the permissions check fails |
2131
2132**示例:**
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
2149暂停下载任务,异步方法,使用promise形式返回结果。
2150
2151> **说明:**
2152>
2153> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[suspend<sup>9+</sup>](#suspend9)替代。
2154
2155**需要权限**:ohos.permission.INTERNET
2156
2157**系统能力**:SystemCapability.MiscServices.Download
2158
2159**返回值:**
2160
2161  | 类型 | 说明 |
2162  | -------- | -------- |
2163  | Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2164
2165**错误码:**
2166
2167以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2168
2169  | 错误码ID | 错误信息 |
2170  | -------- | -------- |
2171  | 201 | the permissions check fails |
2172
2173**示例:**
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> **说明:**
2189>
2190> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[suspend<sup>9+</sup>](#suspend9-1)替代。
2191
2192暂停下载任务,异步方法,使用callback形式返回结果。
2193
2194**需要权限**:ohos.permission.INTERNET
2195
2196**系统能力**:SystemCapability.MiscServices.Download
2197
2198**参数:**
2199
2200  | 参数名 | 类型 | 必填 | 说明 |
2201  | -------- | -------- | -------- | -------- |
2202  | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当暂停下载任务成功,err为undefined,否则为错误对象。 |
2203
2204**错误码:**
2205
2206以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2207
2208  | 错误码ID | 错误信息 |
2209  | -------- | -------- |
2210  | 201 | the permissions check fails |
2211
2212**示例:**
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
2229重新启动暂停的下载任务,异步方法,使用promise形式返回结果。
2230
2231> **说明:**
2232>
2233> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[restore<sup>9+</sup>](#restore9)替代。
2234
2235**需要权限**:ohos.permission.INTERNET
2236
2237**系统能力**:SystemCapability.MiscServices.Download
2238
2239**返回值:**
2240
2241  | 类型 | 说明 |
2242  | -------- | -------- |
2243  | Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
2244
2245**错误码:**
2246
2247以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2248
2249  | 错误码ID | 错误信息 |
2250  | -------- | -------- |
2251  | 201 | the permissions check fails |
2252
2253**示例:**
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> **说明:**
2269>
2270> 从API Version 7开始支持,从API Version 9开始不再维护,建议使用[restore<sup>9+</sup>](#restore9-1)替代。
2271
2272重新启动暂停的下载任务,异步方法,使用callback形式返回结果。
2273
2274**需要权限**:ohos.permission.INTERNET
2275
2276**系统能力**:SystemCapability.MiscServices.Download
2277
2278**参数:**
2279
2280  | 参数名 | 类型 | 必填 | 说明 |
2281  | -------- | -------- | -------- | -------- |
2282  | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当重新启动已暂停的下载任务成功,err为undefined,否则为错误对象。 |
2283
2284**错误码:**
2285
2286以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2287
2288  | 错误码ID | 错误信息 |
2289  | -------- | -------- |
2290  | 201 | the permissions check fails |
2291
2292**示例:**
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
2306下载任务的配置信息。
2307
2308**系统能力**:SystemCapability.MiscServices.Download
2309
2310| 名称 | 类型 | 必填 | 说明 |
2311| -------- | -------- | -------- | -------- |
2312| url | string | 是 | 资源地址,其最大长度为2048个字符。 |
2313| header | Object | 否 | 添加要包含在下载请求中的HTTPS标志头。|
2314| enableMetered | boolean | 否 | 设置是否允许在按流量计费的连接下下载(默认使用false)。Wi-Fi为非计费网络,数据流量为计费网络。<br/>-&nbsp;true:是<br/>-&nbsp;false:否 |
2315| enableRoaming | boolean | 否 | 设置是否允许在漫游网络中下载(默认使用false)。 <br/>-&nbsp;true:是<br/>-&nbsp;false:否|
2316| description | string | 否 | 设置下载会话的描述。 |
2317| filePath<sup>7+</sup> | string | 否 | 设置下载路径。默认为调用方(即传入的context)对应的缓存路径。默认文件名从url的最后一个"/"后截取。<br/>-&nbsp;FA模型下使用[context](../apis-ability-kit/js-apis-inner-app-context.md#contextgetcachedir) 获取应用存储路径。<br/>-&nbsp;Stage模型下使用[AbilityContext](../apis-ability-kit/js-apis-inner-application-context.md) 类获取文件路径。|
2318| networkType | number | 否 | 设置允许下载的网络类型(默认使用NETWORK_MOBILE&NETWORK_WIFI)。<br/>-&nbsp;NETWORK_MOBILE:0x00000001<br/>-&nbsp;NETWORK_WIFI:0x00010000|
2319| title | string | 否 | 设置下载任务名称。 |
2320| background<sup>9+</sup> | boolean | 否 | 后台任务通知开关,开启后可在通知中显示下载状态(默认使用false)。 |
2321
2322
2323## DownloadInfo<sup>7+</sup>
2324下载任务信息,[getTaskInfo<sup>9+</sup>](#gettaskinfo9)接口的回调参数。
2325
2326**系统能力**:SystemCapability.MiscServices.Download
2327
2328| 名称 | 类型 |必填 |  说明 |
2329| -------- | -------- | -------- | -------- |
2330| downloadId | number |是 | 下载任务ID。 |
2331| failedReason | number|是 | 下载失败原因,可以是任何[下载任务的错误码](#下载任务的错误码)常量。 |
2332| fileName | string |是| 下载的文件名。 |
2333| filePath | string |是| 存储文件的URI。 |
2334| pausedReason | number |是| 会话暂停的原因,可以是任何[下载任务暂停原因](#下载任务暂停原因)常量。 |
2335| status | number |是| 下载状态码,可以是任何[下载任务状态码](#下载任务状态码)常量。 |
2336| targetURI | string |是| 下载文件的URI。 |
2337| downloadTitle | string |是| 下载任务名称。 |
2338| downloadTotalBytes | number |是| 下载的文件的总大小,单位为字节。 |
2339| description | string |是| 待下载任务的描述信息。 |
2340| downloadedBytes | number |是| 实时下载大小,单位为字节。 |
2341
2342## Action<sup>10+</sup>  
2343
2344定义操作选项。
2345
2346**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2347
2348**系统能力**:SystemCapability.Request.FileTransferAgent
2349
2350| 名称 | 值 |说明 |
2351| -------- | -------- |-------- |
2352| DOWNLOAD | 0 |表示下载任务。 |
2353| UPLOAD | 1 |表示上传任务。 |
2354
2355
2356## Mode<sup>10+</sup>  
2357定义模式选项。<br>
2358前端任务在应用切换到后台一段时间后失败/暂停;后台任务不受影响。
2359
2360**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2361
2362**系统能力**:SystemCapability.Request.FileTransferAgent
2363
2364| 名称 | 值 |说明 |
2365| -------- | -------- |-------- |
2366| BACKGROUND | 0 |表示后台任务。 |
2367| FOREGROUND | 1 |表示前端任务。 |
2368
2369## Network<sup>10+</sup>  
2370
2371定义网络选项。<br>
2372网络不满足设置条件时,未执行的任务等待执行,执行中的任务失败/暂停。
2373
2374**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2375
2376**系统能力**:SystemCapability.Request.FileTransferAgent
2377
2378| 名称 | 值 |说明 |
2379| -------- | -------- |-------- |
2380| ANY | 0 |表示不限网络类型。 |
2381| WIFI | 1 |表示无线网络。 |
2382| CELLULAR | 2 |表示蜂窝数据网络。 |
2383
2384## BroadcastEvent<sup>11+</sup>
2385
2386定义自定义系统事件。用户可以使用公共事件接口获取该事件。
2387上传下载 SA 具有 'ohos.permission.SEND_TASK_COMPLETE_EVENT' 该权限,用户可以配置事件的 metadata 指向的二级配置文件来拦截其他事件发送者。
2388
2389使用 CommonEventData 类型传输公共事件相关数据。成员的内容填写和 [CommonEventData介绍](js-apis-inner-commonEvent-commonEventData.md) 介绍的有所区别,其中 CommonEventData.code 表示任务的状态,目前为 0x40 COMPLETE 或 0x41 FAILED; CommonEventData.data 表示任务的 taskId。
2390
2391<!--Del-->
2392事件配置信息请参考[静态订阅公共事件](../../basic-services/common-event/common-event-static-subscription.md)。<!--DelEnd-->
2393
2394**系统能力**:SystemCapability.Request.FileTransferAgent
2395
2396| 名称 | 值 | 说明        |
2397| -------- | ------- |-----------|
2398| COMPLETE | 'ohos.request.event.COMPLETE' | 表示任务完成事件。 |
2399
2400## FileSpec<sup>10+</sup> 
2401表单项的文件信息。
2402
2403**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2404
2405**系统能力**:SystemCapability.Request.FileTransferAgent
2406
2407| 名称 | 类型 | 必填 | 说明 |
2408| -------- | -------- | -------- | -------- |
2409| path | string | 是 | 文件路径:<br/>-相对路径,位于调用方的缓存路径下,如"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html"。<br/>-internal协议路径,支持"internal://"及其子路径,internal为调用方(即传入的context)对应路径,"internal://cache"对应context.cacheDir。如"internal://cache/path/to/file.txt"。<br/>-应用沙箱目录,只支持到base及其子目录下,如"/data/storage/el1/base/path/to/file.txt"。<br/>-file协议路径,必须匹配应用包名,只支持到base及其子目录下,如"file://com.example.test/data/storage/el2/base/file.txt"。<br/>-用户公共文件,如"file://media/Photo/path/to/file.img"。仅支持前端任务。 |
2410| mimeType | string | 否 | 文件的mimetype通过文件名获取。 |
2411| filename | string | 否 | 文件名,默认值通过路径获取。 |
2412| extras | object | 否 | 文件信息的附加内容。 |
2413
2414
2415## FormItem<sup>10+</sup> 
2416任务的表单项信息。
2417
2418**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2419
2420**系统能力**:SystemCapability.Request.FileTransferAgent
2421
2422| 名称 | 类型 | 必填 | 说明 |
2423| -------- | -------- | -------- | -------- |
2424| name | string | 是 | 表单参数名。 |
2425| value | string \| [FileSpec](#filespec10) \| Array&lt;[FileSpec](#filespec10)&gt; | 是 | 表单参数值。 |
2426
2427
2428## Config<sup>10+</sup> 
2429上传/下载任务的配置信息。
2430
2431**系统能力**:SystemCapability.Request.FileTransferAgent
2432
2433| 名称 | 类型 | 必填 | 说明 |
2434| -------- | -------- | -------- | -------- |
2435| action | [Action](#action10) | 是 | 任务操作选项。<br/>-UPLOAD表示上传任务。<br/>-DOWNLOAD表示下载任务。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2436| url | string | 是 | 资源地址,其最大长度为2048个字符。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2437| title | string | 否 | 任务标题,其最大长度为256个字符,默认值为小写的 upload 或 download,与上面的 action 保持一致。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2438| description | string | 否 | 任务的详细信息,其最大长度为1024个字符,默认值为空字符串。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2439| mode | [Mode](#mode10) | 否 | 任务模式,默认为后台任务。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2440| overwrite | boolean | 否 | 下载过程中路径已存在时的解决方案选择,默认为false。<br/>- true,覆盖已存在的文件。<br/>- false,下载失败。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2441| method | string | 否 | 上传或下载的HTTP标准方法,包括GET、POST和PUT,不区分大小写。<br/>-上传时,使用PUT或POST,默认值为PUT。<br/>-下载时,使用GET或POST,默认值为GET。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2442| headers | object | 否 | 添加要包含在任务中的HTTP协议标志头。<br/>-对于上传请求,默认的Content-Type为"multipart/form-data"。<br/>-对于下载请求,默认的Content-Type为"application/json"。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2443| data | string \| Array&lt;[FormItem](#formitem10)&gt; | 否 | -下载时,data为字符串类型,通常使用json(object将被转换为json文本),默认为空。<br/>-上传时,data是表单项数组Array&lt;[FormItem](#formitem10)&gt;,默认为空。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2444| saveas | string | 否 | 保存下载文件的路径,包括如下几种:<br/>-相对路径,位于调用方的缓存路径下,如"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html"。<br/>-internal协议路径,支持"internal://"及其子路径,internal为调用方(即传入的context)对应路径,"internal://cache"对应context.cacheDir。如"internal://cache/path/to/file.txt"。<br/>-应用沙箱目录,只支持到base及其子目录下,如"/data/storage/el1/base/path/to/file.txt"。<br/>-file协议路径,必须匹配应用包名,只支持到base及其子目录下,如"file://com.example.test/data/storage/el2/base/file.txt"。<br/>默认为调用方(即传入的context)对应的缓存路径。默认文件名从url的最后一个"/"后截取。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2445| network | [Network](#network10) | 否 | 网络选项,当前支持无线网络WIFI和蜂窝数据网络CELLULAR,默认为ANY(WIFI或CELLULAR)。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2446| metered | boolean | 否 | 是否允许在按流量计费的网络中工作,默认为false。<br/>-true:是 <br/>-false:否<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2447| roaming | boolean | 否 | 是否允许在漫游网络中工作,默认为true。<br/>-true:是 <br/>-false:否<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2448| retry | boolean | 否 | 是否为后台任务启用自动重试,仅应用于后台任务,默认为true。<br/>-true:是 <br/>-false:否<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2449| redirect | boolean | 否 | 是否允许重定向,默认为true。<br/>-true:是 <br/>-false:否<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2450| proxy<sup>12+</sup> | string | 否 | 设置代理地址,其最大长度为512个字符,默认为空。<br/>代理地址格式:"http://\<domain or address\>:\<port\>" |
2451| index | number | 否 | 任务的路径索引,通常用于任务断点续传,默认为0。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2452| begins | number | 否 | 文件起点,通常用于断点续传。默认值为0,取值为闭区间。<br/>-下载时,请求读取服务器开始下载文件时的起点位置(http协议中设置"Range"选项)。<br/>-上传时,在上传开始时读取。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2453| ends | number | 否 | 文件终点,通常用于断点续传。默认值为-1,取值为闭区间。<br/>-下载时,请求读取服务器开始下载文件时的结束位置(http协议中设置"Range"选项)。<br/>-上传时,在上传时结束读取。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2454| gauge | boolean | 否 | 后台任务的过程进度通知策略,仅应用于后台任务,默认值为false。<br/>-false:代表仅完成或失败的通知。<br/>-true,发出每个进度已完成或失败的通知。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2455| precise | boolean | 否 | -如果设置为true,在上传/下载无法获取文件大小时任务失败。<br/>-如果设置为false,将文件大小设置为-1时任务继续。<br/>默认值为false。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2456| token | string | 否 | 当创建了一个带有token的任务后,token则为正常查询期间必须提供的,否则将无法通过查询进行检索。其最小为8个字节,最大为2048个字节。默认为空。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2457| priority<sup>11+</sup> | number | 否 | 任务的优先级。任务模式相同的情况下,该配置项的数字越小优先级越高,默认值为0。 |
2458| extras | object | 否 | 配置的附加功能,默认为空。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
2459
2460## State<sup>10+</sup>  
2461
2462定义任务当前的状态。
2463
2464**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2465
2466**系统能力**:SystemCapability.Request.FileTransferAgent
2467
2468| 名称 | 值 |说明 |
2469| -------- | -------- |-------- |
2470| INITIALIZED | 0x00 |通过配置信息([Config](#config10))创建初始化任务。 |
2471| WAITING | 0x10 |表示任务缺少运行或重试的资源与网络状态不匹配。 |
2472| RUNNING | 0x20 |表示正在处理的任务。 |
2473| RETRYING | 0x21 |表示任务至少失败一次,现在正在再次处理中。 |
2474| PAUSED | 0x30 |表示任务暂停,通常后续会恢复任务。 |
2475| STOPPED | 0x31 |表示任务停止。 |
2476| COMPLETED | 0x40 |表示任务完成。 |
2477| FAILED | 0x41 |表示任务失败。 |
2478| REMOVED | 0x50 |表示任务移除。 |
2479
2480
2481## Progress<sup>10+</sup> 
2482任务进度的数据结构。
2483
2484**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2485
2486**系统能力**:SystemCapability.Request.FileTransferAgent
2487
2488| 名称 | 类型 | 必填 | 说明                                                                  |
2489| -------- | -------- | -------- |---------------------------------------------------------------------|
2490| state | [State](#state10) | 是 | 任务当前的状态。                                                            |
2491| index | number | 是 | 任务中当前正在处理的文件索引。                                                     |
2492| processed | number | 是 | 任务中当前文件的已处理数据大小,单位为字节。                                               |
2493| sizes | Array&lt;number&gt; | 是 | 任务中文件的大小,单位为字节。在下载过程中,若服务器使用 chunk 方式传输导致无法从请求头中获取文件总大小时,sizes 为 -1。 |
2494| extras | object | 否 | 交互的额外内容,例如来自服务器的响应的header和body。                                     |
2495
2496
2497## Faults<sup>10+</sup>  
2498
2499定义任务失败的原因。
2500
2501**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2502
2503**系统能力**:SystemCapability.Request.FileTransferAgent
2504
2505| 名称 | 值 | 说明                                                                             |
2506| -------- | -------- |--------------------------------------------------------------------------------|
2507| OTHERS | 0xFF | 表示其他故障。                                                                        |
2508| DISCONNECTED | 0x00 | 表示网络断开连接。                                                                      |
2509| TIMEOUT | 0x10 | 表示任务超时。                                                                        |
2510| PROTOCOL | 0x20 | 表示协议错误,例如:服务器内部错误(500)、无法处理的数据区间(416)等。                                        |
2511| PARAM<sup>12+</sup> | 0x30 | 表示参数错误,例如url格式错误等。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。          |
2512| FSIO | 0x40 | 表示文件系统io错误,例如打开/查找/读取/写入/关闭。                                                   |
2513| DNS<sup>12+</sup> | 0x50 | 表示DNS解析错误。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。                  |
2514| TCP<sup>12+</sup> | 0x60 | 表示TCP连接错误。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。              |
2515| SSL<sup>12+</sup> | 0x70 | 表示SSL连接错误,例如证书错误、证书校验失败错误等。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
2516| REDIRECT<sup>12+</sup> | 0x80 | 表示重定向错误。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。                    |
2517
2518> **说明:**
2519>
2520> API version 12及以下版本,只支持串行的尝试连接域名相关ip,且不支持单个ip的连接时间控制,如果DNS返回的首个ip是阻塞的,可能握手超时造成TIMEOUT错误。
2521
2522## Filter<sup>10+</sup>
2523过滤条件。
2524
2525**系统能力**:SystemCapability.Request.FileTransferAgent
2526
2527| 名称 | 类型 | 必填 | 说明 |
2528| -------- | -------- | -------- | -------- |
2529| before | number | 否 | 结束的Unix时间戳(毫秒),默认为调用时刻。 |
2530| after | number | 否 | 开始的Unix时间戳(毫秒),默认值为调用时刻减24小时。 |
2531| state | [State](#state10) | 否 | 指定任务的状态。 |
2532| action | [Action](#action10) | 否 | 任务操作选项。<br/>-UPLOAD表示上传任务。<br/>-DOWNLOAD表示下载任务。 |
2533| mode | [Mode](#mode10) | 否 | 任务模式。<br/>-FOREGROUND表示前端任务。<br/>-BACKGROUND表示后台任务。<br/>-如果未填写,则查询所有任务。 |
2534
2535## TaskInfo<sup>10+</sup> 
2536查询结果的任务信息数据结构,提供普通查询和系统查询,两种字段的可见范围不同。
2537
2538**系统能力**:SystemCapability.Request.FileTransferAgent
2539
2540| 名称 | 类型 | 必填 | 说明 |
2541| -------- | -------- | -------- | -------- |
2542| saveas | string | 否 | 保存下载文件的路径。 |
2543| url | string | 否 | 任务的url。<br/>- 通过[request.agent.show<sup>10+</sup>](#requestagentshow10-1)、[request.agent.touch<sup>10+</sup>](#requestagenttouch10-1)进行查询。 |
2544| data | string \| Array&lt;[FormItem](#formitem10)&gt; | 否 | 任务值。<br/>- 通过[request.agent.show<sup>10+</sup>](#requestagentshow10-1)、[request.agent.touch<sup>10+</sup>](#requestagenttouch10-1)。 |
2545| tid | string | 是 | 任务id。 |
2546| title | string | 是 | 任务标题。 |
2547| description | string | 是 | 任务描述。 |
2548| action | [Action](#action10) | 是 | 任务操作选项。<br/>-UPLOAD表示上传任务。<br/>-DOWNLOAD表示下载任务。 |
2549| mode | [Mode](#mode10) | 是 | 指定任务模式。<br/>-FOREGROUND表示前端任务。<br/>-BACKGROUND表示后台任务。 |
2550| priority<sup>11+</sup> | number | 是 | 任务配置中的优先级。前端任务的优先级比后台任务高。相同模式的任务,数字越小优先级越高。 |
2551| mimeType | string | 是 | 任务配置中的mimetype。 |
2552| progress | [Progress](#progress10) | 是 | 任务的过程进度。 |
2553| gauge | boolean | 是 | 后台任务的进度通知策略。 |
2554| ctime | number | 是 | 创建任务的Unix时间戳(毫秒),由当前设备的系统生成。<br/>说明:使用[request.agent.search<sup>10+</sup>](#requestagentsearch10-1)进行查询时,该值需处于[after,before]区间内才可正常查询到任务id,before和after信息详见[Filter](#filter10)。
2555| mtime | number | 是 | 任务状态改变时的Unix时间戳(毫秒),由当前设备的系统生成。|
2556| retry | boolean | 是 | 任务的重试开关,仅应用于后台任务。 |
2557| tries | number | 是 | 任务的尝试次数。 |
2558| faults | [Faults](#faults10) | 是 | 任务的失败原因。|
2559| reason | string | 是 | 等待/失败/停止/暂停任务的原因。|
2560| extras | object | 否 | 任务的额外部分。|
2561
2562
2563## HttpResponse<sup>12+</sup> 
2564任务响应头的数据结构。
2565
2566**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2567
2568**系统能力**:SystemCapability.Request.FileTransferAgent
2569
2570| 名称 | 类型 | 必填 | 说明 |
2571| -------- | -------- | -------- | -------- |
2572| version | string | 是 | Http版本。 |
2573| statusCode | number | 是 | Http响应状态码。 |
2574| reason | string | 是 | Http响应原因。|
2575| headers | Map&lt;string, Array&lt;string&gt;&gt; | 是 | Http响应头部。 |
2576
2577## Task<sup>10+</sup> 
2578上传或下载任务。使用该方法前需要先获取Task对象,promise形式通过[request.agent.create<sup>10+</sup>](#requestagentcreate10-1)获取,callback形式通过[request.agent.create<sup>10+</sup>](#requestagentcreate10)获取。
2579
2580### 属性
2581包括任务id和任务的配置信息。
2582
2583**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2584
2585**系统能力**:SystemCapability.Request.FileTransferAgent
2586
2587| 名称 | 类型 | 必填 | 说明 |
2588| -------- | -------- | -------- | -------- |
2589| tid | string | 是 | 任务id,在系统上是唯一的,由系统自动生成。 |
2590| config | [Config](#config10) | 是 | 任务的配置信息。 |
2591
2592
2593### on('progress')<sup>10+</sup>
2594
2595on(event: 'progress', callback: (progress: [Progress](#progress10)) =&gt; void): void
2596
2597订阅任务进度的事件,异步方法,使用callback形式返回结果。
2598
2599**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2600
2601**系统能力**:SystemCapability.Request.FileTransferAgent
2602
2603**参数:**
2604
2605  | 参数名 | 类型 | 必填 | 说明 |
2606  | -------- | -------- | -------- | -------- |
2607  | event | string | 是 | 订阅的事件类型。<br>- 取值为'progress',表示任务进度。 |
2608  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。|
2609
2610**错误码:**
2611
2612以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2613
2614  | 错误码ID | 错误信息 |
2615  | -------- | -------- |
2616  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2617
2618**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
2666>
2667> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
2668
2669### on('completed')<sup>10+</sup>
2670
2671on(event: 'completed', callback: (progress: [Progress](#progress10)) =&gt; void): void
2672
2673订阅任务完成事件,异步方法,使用callback形式返回结果。
2674
2675**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2676
2677**系统能力**:SystemCapability.Request.FileTransferAgent
2678
2679**参数:**
2680
2681  | 参数名 | 类型 | 必填 | 说明 |
2682  | -------- | -------- | -------- | -------- |
2683  | event | string | 是 | 订阅的事件类型。<br>- 取值为'completed',表示任务完成。 |
2684  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 |
2685
2686**错误码:**
2687
2688以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2689
2690  | 错误码ID | 错误信息 |
2691  | -------- | -------- |
2692  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2693
2694**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
2742>
2743> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
2744
2745### on('failed')<sup>10+</sup>
2746
2747on(event: 'failed', callback: (progress: [Progress](#progress10)) =&gt; void): void
2748
2749订阅任务失败事件,异步方法,使用callback形式返回结果。可通过调用[request.agent.show<sup>10+</sup>](#requestagentshow10-1)查看错误原因。
2750
2751**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2752
2753**系统能力**:SystemCapability.Request.FileTransferAgent
2754
2755**参数:**
2756
2757  | 参数名 | 类型 | 必填 | 说明 |
2758  | -------- | -------- | -------- | -------- |
2759  | event | string | 是 | 订阅的事件类型。<br>- 取值为'failed',表示任务失败。 |
2760  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 |
2761
2762**错误码:**
2763
2764以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
2765
2766  | 错误码ID | 错误信息 |
2767  | -------- | -------- |
2768  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2769
2770**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
2818>
2819> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
2820
2821### on('pause')<sup>11+</sup>
2822
2823on(event: 'pause', callback: (progress: [Progress](#progress10)) =&gt; void): void
2824
2825订阅任务暂停事件,异步方法,使用callback形式返回结果。
2826
2827**系统能力**:SystemCapability.Request.FileTransferAgent
2828
2829**参数:**
2830
2831  | 参数名 | 类型 | 必填 | 说明 |
2832  | -------- | -------- | -------- | -------- |
2833  | event | string | 是 | 订阅的事件类型。<br>- 取值为'pause',表示任务暂停。 |
2834  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 |
2835
2836**错误码:**
2837
2838以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
2839
2840  | 错误码ID | 错误信息 |
2841  | -------- | -------- |
2842  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2843
2844**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
2892>
2893> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
2894
2895### on('resume')<sup>11+</sup>
2896
2897on(event: 'resume', callback: (progress: [Progress](#progress10)) =&gt; void): void
2898
2899订阅任务恢复事件,异步方法,使用callback形式返回结果。
2900
2901**系统能力**:SystemCapability.Request.FileTransferAgent
2902
2903**参数:**
2904
2905  | 参数名 | 类型 | 必填 | 说明 |
2906  | -------- | -------- | -------- | -------- |
2907  | event | string | 是 | 订阅的事件类型。<br>- 取值为'resume',表示任务恢复。 |
2908  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 |
2909
2910**错误码:**
2911
2912以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
2913
2914  | 错误码ID | 错误信息 |
2915  | -------- | -------- |
2916  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2917
2918**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
2966>
2967> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
2968
2969### on('remove')<sup>11+</sup>
2970
2971on(event: 'remove', callback: (progress: [Progress](#progress10)) =&gt; void): void
2972
2973订阅任务删除事件,异步方法,使用callback形式返回结果。
2974
2975**系统能力**:SystemCapability.Request.FileTransferAgent
2976
2977**参数:**
2978
2979  | 参数名 | 类型 | 必填 | 说明 |
2980  | -------- | -------- | -------- | -------- |
2981  | event | string | 是 | 订阅的事件类型。<br>- 取值为'remove',表示任务删除。 |
2982  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 |
2983
2984**错误码:**
2985
2986以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
2987
2988  | 错误码ID | 错误信息 |
2989  | -------- | -------- |
2990  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
2991
2992**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
3040>
3041> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3042
3043### on('response')<sup>12+</sup>
3044
3045on(event: 'response', callback: Callback&lt;HttpResponse&gt;): void
3046
3047订阅任务响应头,异步方法,使用callback形式返回结果。
3048
3049**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3050
3051**系统能力**:SystemCapability.Request.FileTransferAgent
3052
3053**参数:**
3054
3055  | 参数名 | 类型 | 必填 | 说明 |
3056  | -------- | -------- | -------- | -------- |
3057  | event | string | 是 | 订阅的事件类型。<br>- 取值为'response',表示任务响应。 |
3058  | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务响应头的数据结构。 |
3059
3060**错误码:**
3061
3062以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
3063
3064  | 错误码ID | 错误信息 |
3065  | -------- | -------- |
3066  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3067
3068**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
3116>
3117> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3118
3119### off('progress')<sup>10+</sup>
3120
3121off(event: 'progress', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3122
3123取消订阅任务进度事件。
3124
3125**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3126
3127**系统能力**:SystemCapability.Request.FileTransferAgent
3128
3129**参数:**
3130
3131  | 参数名 | 类型 | 必填 | 说明 |
3132  | -------- | -------- | -------- | -------- |
3133  | event | string | 是 | 订阅的事件类型。<br>- 取值为'progress',表示任务进度。 |
3134  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3135
3136**错误码:**
3137
3138以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3139
3140  | 错误码ID | 错误信息 |
3141  | -------- | -------- |
3142  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3143
3144**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3189    task.off('progress', createOffCallback1);
3190    //表示取消订阅任务进度的所有回调
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> **说明:**
3200>
3201> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3202
3203### off('completed')<sup>10+</sup>
3204
3205off(event: 'completed', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3206
3207取消订阅任务完成事件。
3208
3209**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3210
3211**系统能力**:SystemCapability.Request.FileTransferAgent
3212
3213**参数:**
3214
3215  | 参数名 | 类型 | 必填 | 说明 |
3216  | -------- | -------- | -------- | -------- |
3217  | event | string | 是 | 订阅的事件类型。<br>- 取值为'completed',表示任务完成。 |
3218  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3219
3220**错误码:**
3221
3222以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3223
3224  | 错误码ID | 错误信息 |
3225  | -------- | -------- |
3226  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3227
3228**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3273    task.off('completed', createOffCallback1);
3274    //表示取消订阅任务完成的所有回调
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> **说明:**
3284>
3285> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3286
3287### off('failed')<sup>10+</sup>
3288
3289off(event: 'failed', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3290
3291取消订阅任务失败事件。
3292
3293**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3294
3295**系统能力**:SystemCapability.Request.FileTransferAgent
3296
3297**参数:**
3298
3299  | 参数名 | 类型 | 必填 | 说明 |
3300  | -------- | -------- | -------- | -------- |
3301  | event | string | 是 | 订阅的事件类型。<br>- 取值为'failed',表示任务失败。 |
3302  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3303
3304**错误码:**
3305
3306以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3307
3308  | 错误码ID | 错误信息 |
3309  | -------- | -------- |
3310  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3311
3312**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3357    task.off('failed', createOffCallback1);
3358    //表示取消订阅任务失败的所有回调
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> **说明:**
3368>
3369> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3370
3371### off('pause')<sup>11+</sup>
3372
3373off(event: 'pause', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3374
3375取消订阅任务暂停事件。
3376
3377**系统能力**:SystemCapability.Request.FileTransferAgent
3378
3379**参数:**
3380
3381  | 参数名 | 类型 | 必填 | 说明 |
3382  | -------- | -------- | -------- | -------- |
3383  | event | string | 是 | 订阅的事件类型。<br>- 取值为'pause',表示任务暂停。 |
3384  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3385
3386**错误码:**
3387
3388以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
3389
3390  | 错误码ID | 错误信息 |
3391  | -------- | -------- |
3392  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3393
3394**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3439    task.off('pause', createOffCallback1);
3440    //表示取消订阅任务暂停的所有回调
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> **说明:**
3450>
3451> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3452
3453### off('resume')<sup>11+</sup>
3454
3455off(event: 'resume', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3456
3457取消订阅任务恢复事件。
3458
3459**系统能力**:SystemCapability.Request.FileTransferAgent
3460
3461**参数:**
3462
3463  | 参数名 | 类型 | 必填 | 说明 |
3464  | -------- | -------- | -------- | -------- |
3465  | event | string | 是 | 订阅的事件类型。<br>- 取值为'resume',表示任务恢复。 |
3466  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3467
3468**错误码:**
3469
3470以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
3471
3472  | 错误码ID | 错误信息 |
3473  | -------- | -------- |
3474  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3475
3476**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3521    task.off('resume', createOffCallback1);
3522    //表示取消订阅任务恢复的所有回调
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> **说明:**
3532>
3533> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3534
3535### off('remove')<sup>11+</sup>
3536
3537off(event: 'remove', callback?: (progress: [Progress](#progress10)) =&gt; void): void
3538
3539取消订阅任务删除事件。
3540
3541**系统能力**:SystemCapability.Request.FileTransferAgent
3542
3543**参数:**
3544
3545  | 参数名 | 类型 | 必填 | 说明 |
3546  | -------- | -------- | -------- | -------- |
3547  | event | string | 是 | 订阅的事件类型。<br>- 取值为'remove',表示任务删除。 |
3548  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3549
3550**错误码:**
3551
3552以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
3553
3554  | 错误码ID | 错误信息 |
3555  | -------- | -------- |
3556  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3557
3558**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3603    task.off('remove', createOffCallback1);
3604    //表示取消订阅任务移除的所有回调
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> **说明:**
3614>
3615> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3616
3617### off('response')<sup>12+</sup>
3618
3619off(event: 'response', callback?: Callback&lt;HttpResponse&gt;): void
3620
3621取消订阅任务响应头。
3622
3623**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3624
3625**系统能力**:SystemCapability.Request.FileTransferAgent
3626
3627**参数:**
3628
3629  | 参数名 | 类型 | 必填 | 说明 |
3630  | -------- | -------- | -------- | -------- |
3631  | event | string | 是 | 订阅的事件类型。<br>- 取值为'response',表示任务响应。 |
3632  | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 |
3633
3634**错误码:**
3635
3636以下错误码的详细介绍请参见[通用错误码说明文档](../errorcode-universal.md)。
3637
3638  | 错误码ID | 错误信息 |
3639  | -------- | -------- |
3640  | 401 | Parameter error. Possible causes: 1. Missing mandatory parameters 2. Incorrect parameter type 3. Parameter verification failed |
3641
3642**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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    //表示取消createOffCallback1的订阅
3687    task.off('response', createOffCallback1);
3688    //表示取消订阅任务移除的所有回调
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> **说明:**
3698>
3699> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3700
3701### start<sup>10+</sup>
3702
3703start(callback: AsyncCallback&lt;void&gt;): void
3704
3705以下状态的任务可以被启动:
37061. 刚被 request.agent.create 接口创建的任务
37072. 使用 request.agent.create 接口创建的已经失败或者停止的下载任务
3708
3709**需要权限**:ohos.permission.INTERNET
3710
3711**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3712
3713**系统能力**:SystemCapability.Request.FileTransferAgent
3714
3715**参数:**
3716
3717  | 参数名 | 类型 | 必填 | 说明 |
3718  | -------- | -------- | -------- | -------- |
3719  | callback | function | 是 | 回调函数。当开启任务成功,err为undefined,否则为错误对象。 |
3720
3721**错误码:**
3722
3723以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3724
3725  | 错误码ID | 错误信息 |
3726  | -------- | -------- |
3727  | 201 | Permission denied. |
3728  | 13400003 | task service ability error. |
3729  | 21900007 | task state error. |
3730
3731**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
3773>
3774> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3775
3776### start<sup>10+</sup>
3777
3778start(): Promise&lt;void&gt;
3779
3780以下状态的任务可以被启动:
37811. 刚被request.agent.create 接口创建的任务
37822. 使用request.agent.create 接口创建的已经失败或者停止的下载任务
3783
3784**需要权限**:ohos.permission.INTERNET
3785
3786**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3787
3788**系统能力**:SystemCapability.Request.FileTransferAgent
3789
3790**返回值:** 
3791
3792| 类型                | 说明                      |
3793| ------------------- | ------------------------- |
3794| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
3795
3796**错误码:**
3797
3798以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3799
3800  | 错误码ID | 错误信息 |
3801  | -------- | -------- |
3802  | 201 | Permission denied. |
3803  | 13400003 | task service ability error. |
3804  | 21900007 | task state error. |
3805
3806**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
3846>
3847> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
3848
3849### pause<sup>10+</sup>
3850
3851pause(callback: AsyncCallback&lt;void&gt;): void
3852
3853暂停任务,可以暂停正在等待/正在运行/正在重试的任务。使用callback异步回调。
3854
3855**系统能力**:SystemCapability.Request.FileTransferAgent
3856
3857**参数:**
3858
3859  | 参数名 | 类型 | 必填 | 说明 |
3860  | -------- | -------- | -------- | -------- |
3861  | callback | function | 是 | 回调函数。当暂停任务成功,err为undefined,否则为错误对象。 |
3862
3863**错误码:**
3864
3865以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)。
3866
3867  | 错误码ID | 错误信息 |
3868  | -------- | -------- |
3869  | 13400003 | task service ability error. |
3870  | 21900007 | task state error. |
3871
3872**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
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
3919暂停任务,可以暂停正在等待/正在运行/正在重试的任务。使用Promise异步回调。
3920
3921**系统能力**:SystemCapability.Request.FileTransferAgent
3922
3923**返回值:** 
3924
3925| 类型                | 说明                      |
3926| ------------------- | ------------------------- |
3927| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
3928
3929**错误码:**
3930
3931以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)。
3932
3933  | 错误码ID | 错误信息 |
3934  | -------- | -------- |
3935  | 13400003 | task service ability error. |
3936  | 21900007 | task state error. |
3937
3938**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
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
3983重新启动任务,可以恢复暂停的任务。使用callback异步回调。
3984
3985**需要权限**:ohos.permission.INTERNET
3986
3987**系统能力**:SystemCapability.Request.FileTransferAgent
3988
3989**参数:**
3990
3991  | 参数名 | 类型 | 必填 | 说明 |
3992  | -------- | -------- | -------- | -------- |
3993  | callback | function | 是 | 回调函数。当重新启动任务成功,err为undefined,否则为错误对象。 |
3994
3995**错误码:**
3996
3997以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
3998
3999  | 错误码ID | 错误信息 |
4000  | -------- | -------- |
4001  | 201 | Permission denied. |
4002  | 13400003 | task service ability error. |
4003  | 21900007 | task state error. |
4004
4005**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
4035    task.pause();
4036    for(let t = Date.now(); Date.now() - t <= 1000;); // 等待1秒再执行下一步操作,以防异步乱序
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
4054重新启动任务,可以恢复暂停的任务。使用Promise异步回调。
4055
4056**需要权限**:ohos.permission.INTERNET
4057
4058**系统能力**:SystemCapability.Request.FileTransferAgent
4059
4060**返回值:** 
4061
4062| 类型                | 说明                      |
4063| ------------------- | ------------------------- |
4064| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
4065
4066**错误码:**
4067
4068以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4069
4070  | 错误码ID | 错误信息 |
4071  | -------- | -------- |
4072  | 201 | Permission denied. |
4073  | 13400003 | task service ability error. |
4074  | 21900007 | task state error. |
4075
4076**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
4106    task.pause();
4107    for(let t = Date.now(); Date.now() - t <= 1000;); // 等待1秒再执行下一步操作,以防异步乱序
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
4123停止任务,可以停止正在运行/正在等待/正在重试的任务。使用callback异步回调。
4124
4125**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4126
4127**系统能力**:SystemCapability.Request.FileTransferAgent
4128
4129**参数:**
4130
4131  | 参数名 | 类型 | 必填 | 说明 |
4132  | -------- | -------- | -------- | -------- |
4133  | callback | function | 是 | 回调函数。当停止任务成功,err为undefined,否则为错误对象。 |
4134
4135**错误码:**
4136
4137以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)。
4138
4139  | 错误码ID | 错误信息 |
4140  | -------- | -------- |
4141  | 13400003 | task service ability error. |
4142  | 21900007 | task state error. |
4143
4144**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
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
4192停止任务,可以停止正在运行/正在等待/正在重试的任务。使用Promise异步回调。
4193
4194**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4195
4196**系统能力**:SystemCapability.Request.FileTransferAgent
4197
4198**返回值:** 
4199
4200| 类型                | 说明                      |
4201| ------------------- | ------------------------- |
4202| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
4203
4204**错误码:**
4205
4206以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)。
4207
4208  | 错误码ID | 错误信息 |
4209  | -------- | -------- |
4210  | 13400003 | task service ability error. |
4211  | 21900007 | task state error. |
4212
4213**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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;); // 等待1秒再执行下一步操作,以防异步乱序
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
4258创建要上传或下载的任务,并将其排入队列。使用callback异步回调。
4259
4260
4261**需要权限**:ohos.permission.INTERNET
4262
4263**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4264
4265**系统能力**:SystemCapability.Request.FileTransferAgent
4266
4267**参数:**
4268
4269  | 参数名 | 类型 | 必填 | 说明 |
4270  | -------- | -------- | -------- | -------- |
4271  | config | [Config](#config10) | 是 | 上传/下载任务的配置信息。 |
4272  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
4273  | callback | AsyncCallback&lt;[Task](#task10)&gt; | 是 | 回调函数。当创建上传或下载任务成功,err为undefined,data为获取到的Task对象;否则为错误对象。 |
4274
4275**错误码:**
4276
4277以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4278
4279  | 错误码ID | 错误信息 |
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**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
4334>
4335> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
4336
4337## request.agent.create<sup>10+</sup>
4338
4339create(context: BaseContext, config: Config): Promise&lt;Task&gt;
4340
4341创建要上传或下载的任务,并将其排入队列。使用Promise异步回调。
4342
4343
4344**需要权限**:ohos.permission.INTERNET
4345
4346**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4347
4348**系统能力**:SystemCapability.Request.FileTransferAgent
4349
4350**参数:**
4351
4352  | 参数名 | 类型 | 必填 | 说明 |
4353  | -------- | -------- | -------- | -------- |
4354  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
4355  | config | [Config](#config10) | 是 | 上传/下载任务的配置信息。 |
4356
4357**返回值:** 
4358
4359| 类型                | 说明                      |
4360| ------------------- | ------------------------- |
4361| Promise&lt;[Task](#task10)&gt; | Promise对象。返回任务配置信息的Promise对象。 |
4362
4363**错误码:**
4364
4365以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4366
4367  | 错误码ID | 错误信息 |
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**示例:**
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', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
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> **说明:**
4420>
4421> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
4422
4423## request.agent.getTask<sup>11+</sup>
4424
4425getTask(context: BaseContext, id: string, token?: string): Promise&lt;Task&gt;
4426
4427根据任务id查询任务。使用Promise异步回调。
4428
4429**系统能力**:SystemCapability.Request.FileTransferAgent
4430
4431**参数:**
4432
4433  | 参数名 | 类型 | 必填 | 说明 |
4434  | -------- | -------- | -------- | -------- |
4435  | context | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 |
4436  | id | string | 是 | 任务id。 |
4437  | token | string | 否 | 任务查询token。 |
4438
4439**返回值:** 
4440
4441| 类型                | 说明                      |
4442| ------------------- | ------------------------- |
4443| Promise&lt;[Task](#task10)&gt; | Promise对象。返回任务配置信息的Promise对象。 |
4444
4445**错误码:**
4446
4447以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4448
4449  | 错误码ID | 错误信息 |
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**示例:**
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
4471移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止。使用callback异步回调。
4472
4473**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4474
4475**系统能力**:SystemCapability.Request.FileTransferAgent
4476
4477**参数:**
4478
4479  | 参数名 | 类型 | 必填 | 说明 |
4480  | -------- | -------- | -------- | -------- |
4481  | id | string | 是 | 任务id。 |
4482  | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当删除指定任务成功,err为undefined,否则为错误对象。 |
4483
4484**错误码:**
4485
4486以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4487
4488  | 错误码ID | 错误信息 |
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**示例:**
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 removing 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
4513移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止,使用Promise异步回调。
4514
4515**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4516
4517**系统能力**:SystemCapability.Request.FileTransferAgent
4518
4519**参数:**
4520
4521  | 参数名 | 类型 | 必填 | 说明 |
4522  | -------- | -------- | -------- | -------- |
4523  | id | string | 是 | 任务id。 |
4524
4525**返回值:** 
4526
4527| 类型                | 说明                      |
4528| ------------------- | ------------------------- |
4529| Promise&lt;void&gt; | Promise对象。无返回结果的Promise对象。 |
4530
4531**错误码:**
4532
4533以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4534
4535  | 错误码ID | 错误信息 |
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**示例:**
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
4558根据任务id查询任务的详细信息。使用callback异步回调。
4559
4560**系统能力**:SystemCapability.Request.FileTransferAgent
4561
4562**参数:**
4563
4564  | 参数名 | 类型 | 必填 | 说明 |
4565  | -------- | -------- | -------- | -------- |
4566  | id | string | 是 | 任务id。 |
4567  | callback | AsyncCallback&lt;[TaskInfo](#taskinfo10)&gt; | 是 | 回调函数。当查询任务操作成功,err为undefined,data为查询到的任务TaskInfo信息;否则为错误对象。 |
4568
4569**错误码:**
4570以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4571
4572  | 错误码ID | 错误信息 |
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**示例:**
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
4597根据任务id查询任务的详细信息。使用Promise异步回调。
4598
4599**系统能力**:SystemCapability.Request.FileTransferAgent
4600
4601**参数:**
4602
4603  | 参数名 | 类型 | 必填 | 说明 |
4604  | -------- | -------- | -------- | -------- |
4605  | id | string | 是 | 任务id。 |
4606
4607**返回值:** 
4608
4609| 类型                | 说明                      |
4610| ------------------- | ------------------------- |
4611| Promise&lt;[TaskInfo](#taskinfo10)&gt; | Promise对象。返回任务详细信息TaskInfo的Promise对象。 |
4612
4613**错误码:**
4614以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4615
4616  | 错误码ID | 错误信息 |
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**示例:**
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
4639根据任务id和token查询任务的详细信息。使用callback异步回调。
4640
4641**系统能力**:SystemCapability.Request.FileTransferAgent
4642
4643**参数:**
4644
4645  | 参数名 | 类型 | 必填 | 说明 |
4646  | -------- | -------- | -------- | -------- |
4647  | id | string | 是 | 任务id。 |
4648  | token | string | 是 | 任务查询token。 |
4649  | callback | AsyncCallback&lt;[TaskInfo](#taskinfo10)&gt; | 是 | 回调函数。当查询任务操作成功,err为undefined,data为查询到的任务TaskInfo信息;否则为错误对象。 |
4650
4651**错误码:**
4652以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4653
4654  | 错误码ID | 错误信息 |
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**示例:**
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
4679根据任务id和token查询任务的详细信息。使用Promise异步回调。
4680
4681**系统能力**:SystemCapability.Request.FileTransferAgent
4682
4683**参数:**
4684
4685  | 参数名 | 类型 | 必填 | 说明 |
4686  | -------- | -------- | -------- | -------- |
4687  | id | string | 是 | 任务id。 |
4688  | token | string | 是 | 任务查询token。 |
4689
4690**返回值:** 
4691
4692| 类型                | 说明                      |
4693| ------------------- | ------------------------- |
4694| Promise&lt;[TaskInfo](#taskinfo10)&gt; | Promise对象。返回任务详细信息TaskInfo的Promise对象。 |
4695
4696**错误码:**
4697以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4698
4699  | 错误码ID | 错误信息 |
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**示例:**
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
4721根据默认[Filter](#filter10)过滤条件查找任务id。使用callback异步回调。
4722
4723**系统能力**:SystemCapability.Request.FileTransferAgent
4724
4725**参数:**
4726
4727  | 参数名 | 类型 | 必填 | 说明 |
4728  | -------- | -------- | -------- | -------- |
4729  | callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | 是 | 回调函数。当根据过滤条件查找任务成功,err为undefined,data为满足条件的任务id;否则为错误对象。 |
4730
4731**错误码:**
4732以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4733
4734  | 错误码ID | 错误信息 |
4735  | -------- | -------- |
4736  | 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed |
4737  | 13400003 | task service ability error. |
4738
4739**示例:**
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
4757根据[Filter](#filter10)过滤条件查找任务id。使用callback异步回调。
4758
4759**系统能力**:SystemCapability.Request.FileTransferAgent
4760
4761**参数:**
4762
4763  | 参数名 | 类型 | 必填 | 说明 |
4764  | -------- | -------- | -------- | -------- |
4765  | filter | [Filter](#filter10) | 是 | 过滤条件。 |
4766  | callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | 是 | 回调函数。当根据过滤条件查找任务成功,err为undefined,data为满足条件的任务id;否则为错误对象。 |
4767
4768**错误码:**
4769以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4770
4771  | 错误码ID | 错误信息 |
4772  | -------- | -------- |
4773  | 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed |
4774  | 13400003 | task service ability error. |
4775
4776**示例:**
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
4799根据[Filter](#filter10)过滤条件查找任务id。使用Promise异步回调。
4800
4801**系统能力**:SystemCapability.Request.FileTransferAgent
4802
4803**参数:**
4804
4805  | 参数名 | 类型 | 必填 | 说明 |
4806  | -------- | -------- | -------- | -------- |
4807  | filter | [Filter](#filter10) | 否 | 过滤条件。 |
4808
4809**返回值:** 
4810
4811| 类型                | 说明                      |
4812| ------------------- | ------------------------- |
4813| Promise&lt;Array&lt;string&gt;&gt; | Promise对象。返回满足条件任务id的Promise对象。 |
4814
4815**错误码:**
4816以下错误码的详细介绍请参见[上传下载错误码](errorcode-request.md)与[通用错误码说明文档](../errorcode-universal.md)。
4817
4818  | 错误码ID | 错误信息 |
4819  | -------- | -------- |
4820  | 401 | parameter error. Possible causes: 1. Incorrect parameter type 2. Parameter verification failed |
4821  | 13400003 | task service ability error. |
4822
4823**示例:**
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
4839
4840
4841