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