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