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