1# @ohos.request (上传下载) 2 3request部件主要给应用提供上传下载文件、后台传输代理的基础能力。 4 5> **说明:** 6> 7> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8 9 10## 导入模块 11 12 13```js 14import request from '@ohos.request'; 15``` 16 17 18 19## Action<sup>10+</sup> 20 21定义操作选项。 22 23**系统能力**: SystemCapability.Request.FileTransferAgent 24 25| 名称 | 值 |说明 | 26| -------- | -------- |-------- | 27| DOWNLOAD | 0 |表示下载任务。 | 28| UPLOAD | 1 |表示上传任务。 | 29 30 31## Mode<sup>10+</sup> 32定义模式选项。 33 34**系统能力**: SystemCapability.Request.FileTransferAgent 35 36| 名称 | 值 |说明 | 37| -------- | -------- |-------- | 38| BACKGROUND | 0 |表示后台任务。 | 39| FOREGROUND | 1 |表示前端任务。 | 40 41## Network<sup>10+</sup> 42 43定义网络选项。 44 45**系统能力**: SystemCapability.Request.FileTransferAgent 46 47| 名称 | 值 |说明 | 48| -------- | -------- |-------- | 49| ANY | 0 |表示不限网络类型。 | 50| WIFI | 1 |表示无线网络。 | 51| CELLULAR | 2 |表示蜂窝数据网络。 | 52 53 54## FileSpec<sup>10+</sup> 55表单项的文件信息。 56 57**系统能力**: SystemCapability.Request.FileTransferAgent 58 59| 名称 | 类型 | 必填 | 说明 | 60| -------- | -------- | -------- | -------- | 61| path | string | 是 | 文件路径位于调用方的缓存文件夹下的相对路径。 | 62| mimeType | string | 否 | 文件的mimetype通过文件名获取。 | 63| filename | string | 否 | 文件名,默认值通过路径获取。 | 64| extras | Object | 否 | 文件信息的附加内容。 | 65 66 67## FormItem<sup>10+</sup> 68任务的表单项信息。 69 70**系统能力**: SystemCapability.Request.FileTransferAgent 71 72| 名称 | 类型 | 必填 | 说明 | 73| -------- | -------- | -------- | -------- | 74| name | string | 是 | 表单参数名。 | 75| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | 是 | 表单参数值。 | 76 77 78## Config<sup>10+</sup> 79上传/下载任务的配置信息。 80 81**系统能力**: SystemCapability.Request.FileTransferAgent 82 83| 名称 | 类型 | 必填 | 说明 | 84| -------- | -------- | -------- | -------- | 85| action | [Action](#action10) | 是 | 任务操作选项。<br/>-UPLOAD表示上传任务。<br/>-DOWNLOAD表示下载任务。 | 86| url | string | 是 | 资源地址,其最大长度为2048个字符。 | 87| title | string | 否 | 任务标题,其最大长度为256个字符,默认值为小写的 upload 或 download,与上面的 action 保持一致。 | 88| description | string | 否 | 任务的详细信息,其最大长度为1024个字符,默认值为空字符串。 | 89| mode | [Mode](#mode10) | 否 | 任务模式,默认为后台任务。<br/>-对于前端任务,有回调通知。<br/>-对于后台任务,有系统通知、检测网络连接、恢复、自动重试功能。 | 90| overwrite | boolean | 否 | 下载过程中路径已存在时的解决方案选择,默认为false。<br/>- true,覆盖已存在的文件。<br/>- false,下载失败。 | 91| method | string | 否 | 上传或下载的HTTP标准方法,包括GET、POST和PUT,不区分大小写。<br/>-上传时,使用PUT或POST,默认值为PUT。<br/>-下载时,使用GET或POST,默认值为GET。 | 92| headers | object | 否 | 添加要包含在任务中的HTTP协议标志头。<br/>-对于上传请求,默认的Content-Type为"multipart/form-data"。<br/>-对于下载请求,默认的Content-Type为"application/json"。 | 93| data | string \| Array<[FormItem](#formitem10)> | 否 | -下载时,data为字符串类型,通常使用json(object将被转换为json文本),默认为空。<br/>-上传时,data是表单项数组Array<[FormItem](#formitem10)>,默认为空。 | 94| saveas | string | 否 | 保存下载文件的路径,包括如下两种:<br/>-相对路径,如"./xxx/yyy/zzz.html"、"xxx/yyy/zzz.html",位于调用方的缓存路径下。<br/>-uri路径,如"datashare://bundle/xxx/yyy/zzz.html",仅对具有访问url路径权限的应用开放。该功能暂不支持。<br/>默认为相对路径,即下载至应用当前缓存路径下。 | 95| network | [Network](#network10) | 否 | 网络选项,当前支持无线网络WIFI和蜂窝数据网络CELLULAR,默认为ANY(WIFI或CELLULAR)。 | 96| metered | boolean | 否 | 是否允许在按流量计费的网络中工作,默认为false。<br/>-true:是 <br/>-false:否| 97| roaming | boolean | 否 | 是否允许在漫游网络中工作,默认为true。<br/>-true:是 <br/>-false:否 | 98| retry | boolean | 否 | 是否为后台任务启用自动重试,仅应用于后台任务,默认为true。<br/>-true:是 <br/>-false:否 | 99| redirect | boolean | 否 | 是否允许重定向,默认为true。<br/>-true:是 <br/>-false:否 | 100| index | number | 否 | 任务的路径索引,通常用于任务断点续传,默认为0。 | 101| begins | number | 否 | 文件起点,通常用于断点续传。默认值为0,取值为闭区间。<br/>-下载时,请求读取服务器开始下载文件时的起点位置(http协议中设置"Range"选项)。<br/>-上传时,在上传开始时读取。 | 102| ends | number | 否 | 文件终点,通常用于断点续传。默认值为-1,取值为闭区间。<br/>-下载时,请求读取服务器开始下载文件时的结束位置(http协议中设置"Range"选项)。<br/>-上传时,在上传时结束读取。 | 103| gauge | boolean | 否 | 后台任务的过程进度通知策略,仅应用于后台任务,默认值为false。<br/>-false:代表仅完成或失败的通知。<br/>-true,发出每个进度已完成或失败的通知。 | 104| precise | boolean | 否 | -如果设置为true,在上传/下载无法获取文件大小时任务失败。<br/>-如果设置为false,将文件大小设置为-1时任务继续。<br/>默认值为false。 | 105| token | string | 否 | 当创建了一个带有token的任务后,token则为正常查询期间必须提供的,否则将无法通过查询进行检索。其最小为8个字节,最大为2048个字节。默认为空。 | 106| extras | object | 否 | 配置的附加功能,默认为空。 | 107 108## State<sup>10+</sup> 109 110定义任务当前的状态。 111 112**系统能力**: SystemCapability.Request.FileTransferAgent 113 114| 名称 | 值 |说明 | 115| -------- | -------- |-------- | 116| INITIALIZED | 0x00 |通过配置信息([Config](#config10))创建初始化任务。 | 117| WAITING | 0x10 |表示任务缺少运行或重试的资源与网络状态不匹配。 | 118| RUNNING | 0x20 |表示正在处理的任务。 | 119| RETRYING | 0x21 |表示任务至少失败一次,现在正在再次处理中。 | 120| PAUSED | 0x30 |表示任务暂停,通常后续会恢复任务。 | 121| STOPPED | 0x31 |表示任务停止。 | 122| COMPLETED | 0x40 |表示任务完成。 | 123| FAILED | 0x41 |表示任务失败。 | 124| REMOVED | 0x50 |表示任务移除。 | 125 126 127## Progress<sup>10+</sup> 128任务进度的数据结构。 129 130**系统能力**: SystemCapability.Request.FileTransferAgent 131 132| 名称 | 类型 | 必填 | 说明 | 133| -------- | -------- | -------- | -------- | 134| state | [State](#state10) | 是 | 任务当前的状态。 | 135| index | number | 是 | 任务中当前正在处理的文件索引。 | 136| processed | number | 是 | 任务中当前文件的已处理数据大小,单位为B。| 137| sizes | Array<number> | 是 | 任务中文件的大小,单位为B。 | 138| extras | object | 否 | 交互的额外内容,例如来自服务器的响应的header和body。 | 139 140 141## Faults<sup>10+</sup> 142 143定义任务失败的原因。 144 145**系统能力**: SystemCapability.Request.FileTransferAgent 146 147| 名称 | 值 |说明 | 148| -------- | -------- |-------- | 149| OTHERS | 0xFF |表示其他故障。 | 150| DISCONNECTED | 0x00 |表示网络断开连接。 | 151| TIMEOUT | 0x10 |表示任务超时。 | 152| PROTOCOL | 0x20 |表示协议错误,例如:服务器内部错误(500)、无法处理的数据区间(416)等。 | 153| FSIO | 0x40 |表示文件系统io错误,例如打开/查找/读取/写入/关闭。 | 154 155 156## Filter<sup>10+</sup> 157过滤条件。 158 159**系统能力**: SystemCapability.Request.FileTransferAgent 160 161| 名称 | 类型 | 必填 | 说明 | 162| -------- | -------- | -------- | -------- | 163| bundle | string | 否 | 指定应用程序的包名,仅对系统应用开放。<br/>**系统接口**:此接口为系统接口。 | 164| before | number | 否 | 结束的Unix时间戳(毫秒),默认为调用时刻。 | 165| after | number | 否 | 开始的Unix时间戳(毫秒),默认值为调用时刻减24小时。 | 166| state | [State](#state10) | 否 | 指定任务的状态。 | 167| action | [Action](#action10) | 否 | 任务操作选项。<br/>-UPLOAD表示上传任务。<br/>-DOWNLOAD表示下载任务。 | 168| mode | [Mode](#mode10) | 否 | 任务模式。<br/>-FOREGROUND表示前端任务。<br/>-BACKGROUND表示后台任务。<br/>-如果未填写,则查询所有任务。 | 169 170 171## Task<sup>10+</sup> 172上传或下载任务。使用该方法前需要先获取Task对象,promise形式通过[request.agent.create<sup>10+</sup>](#requestagentcreate10-1)获取,callback形式通过[request.agent.create<sup>10+</sup>](#requestagentcreate10)获取。 173 174### 属性 175包括任务id和任务的配置信息。 176 177**系统能力**: SystemCapability.Request.FileTransferAgent 178 179| 名称 | 类型 | 必填 | 说明 | 180| -------- | -------- | -------- | -------- | 181| tid | string | 是 | 任务id,在系统上是唯一的,由系统自动生成。 | 182| config | [Config](#config10) | 是 | 任务的配置信息。 | 183 184 185### on('progress')<sup>10+</sup> 186 187on(event: 'progress', callback: (progress: Progress) => void): void 188 189订阅前端任务进度的事件,异步方法,使用callback形式返回结果。 190 191**系统能力**: SystemCapability.Request.FileTransferAgent 192 193**参数:** 194 195 | 参数名 | 类型 | 必填 | 说明 | 196 | -------- | -------- | -------- | -------- | 197 | event | string | 是 | 订阅的事件类型。<br>- 取值为'progress',表示任务进度。 | 198 | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。| 199 200**错误码:** 201 202以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 203 204 | 错误码ID | 错误信息 | 205 | -------- | -------- | 206 | 21900005 | task mode error. | 207 208**示例:** 209 210 ```ts 211 import { BusinessError, request } from '@kit.BasicServicesKit'; 212 213 let attachments: Array<request.agent.FormItem> = [{ 214 name: "taskOnTest", 215 value: { 216 filename: "taskOnTest.avi", 217 mimeType: "application/octet-stream", 218 path: "./taskOnTest.avi", 219 } 220 }]; 221 let config: request.agent.Config = { 222 action: request.agent.Action.UPLOAD, 223 url: 'http://127.0.0.1', 224 title: 'taskOnTest', 225 description: 'Sample code for event listening', 226 mode: request.agent.Mode.FOREGROUND, 227 overwrite: false, 228 method: "PUT", 229 data: attachments, 230 saveas: "./", 231 network: request.agent.Network.CELLULAR, 232 metered: false, 233 roaming: true, 234 retry: true, 235 redirect: true, 236 index: 0, 237 begins: 0, 238 ends: -1, 239 gauge: false, 240 precise: false, 241 token: "it is a secret" 242 }; 243 let createOnCallback = (progress: request.agent.Progress) => { 244 console.info('upload task progress.'); 245 }; 246 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 247 task.on('progress', createOnCallback); 248 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 249 }).catch((err: BusinessError) => { 250 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 251 }); 252 ``` 253 254> **说明:** 255> 256> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 257 258### on('completed')<sup>10+</sup> 259 260on(event: 'completed', callback: (progress: Progress) => void): void 261 262订阅前端任务完成事件,异步方法,使用callback形式返回结果。 263 264**系统能力**: SystemCapability.Request.FileTransferAgent 265 266**参数:** 267 268 | 参数名 | 类型 | 必填 | 说明 | 269 | -------- | -------- | -------- | -------- | 270 | event | string | 是 | 订阅的事件类型。<br>- 取值为'completed',表示任务完成。 | 271 | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 | 272 273**错误码:** 274 275以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 276 277 | 错误码ID | 错误信息 | 278 | -------- | -------- | 279 | 21900005 | task mode error. | 280 281**示例:** 282 283 ```ts 284 import { BusinessError, request } from '@kit.BasicServicesKit'; 285 286 let attachments: Array<request.agent.FormItem> = [{ 287 name: "taskOnTest", 288 value: { 289 filename: "taskOnTest.avi", 290 mimeType: "application/octet-stream", 291 path: "./taskOnTest.avi", 292 } 293 }]; 294 let config: request.agent.Config = { 295 action: request.agent.Action.UPLOAD, 296 url: 'http://127.0.0.1', 297 title: 'taskOnTest', 298 description: 'Sample code for event listening', 299 mode: request.agent.Mode.FOREGROUND, 300 overwrite: false, 301 method: "PUT", 302 data: attachments, 303 saveas: "./", 304 network: request.agent.Network.CELLULAR, 305 metered: false, 306 roaming: true, 307 retry: true, 308 redirect: true, 309 index: 0, 310 begins: 0, 311 ends: -1, 312 gauge: false, 313 precise: false, 314 token: "it is a secret" 315 }; 316 let createOnCallback = (progress: request.agent.Progress) => { 317 console.info('upload task completed.'); 318 }; 319 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 320 task.on('completed', createOnCallback); 321 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 322 }).catch((err: BusinessError) => { 323 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 324 }); 325 ``` 326 327> **说明:** 328> 329> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 330 331### on('failed')<sup>10+</sup> 332 333on(event: 'failed', callback: (progress: Progress) => void): void 334 335订阅前端任务失败事件,异步方法,使用callback形式返回结果。 336 337**系统能力**: SystemCapability.Request.FileTransferAgent 338 339**参数:** 340 341 | 参数名 | 类型 | 必填 | 说明 | 342 | -------- | -------- | -------- | -------- | 343 | event | string | 是 | 订阅的事件类型。<br>- 取值为'failed',表示任务失败。 | 344 | callback | function | 是 | 发生相关的事件时触发该回调方法,返回任务进度的数据结构。 | 345 346**错误码:** 347 348以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 349 350 | 错误码ID | 错误信息 | 351 | -------- | -------- | 352 | 21900005 | task mode error. | 353 354**示例:** 355 356 ```ts 357 import { BusinessError, request } from '@kit.BasicServicesKit'; 358 359 let attachments: Array<request.agent.FormItem> = [{ 360 name: "taskOnTest", 361 value: { 362 filename: "taskOnTest.avi", 363 mimeType: "application/octet-stream", 364 path: "./taskOnTest.avi", 365 } 366 }]; 367 let config: request.agent.Config = { 368 action: request.agent.Action.UPLOAD, 369 url: 'http://127.0.0.1', 370 title: 'taskOnTest', 371 description: 'Sample code for event listening', 372 mode: request.agent.Mode.FOREGROUND, 373 overwrite: false, 374 method: "PUT", 375 data: attachments, 376 saveas: "./", 377 network: request.agent.Network.CELLULAR, 378 metered: false, 379 roaming: true, 380 retry: true, 381 redirect: true, 382 index: 0, 383 begins: 0, 384 ends: -1, 385 gauge: false, 386 precise: false, 387 token: "it is a secret" 388 }; 389 let createOnCallback = (progress: request.agent.Progress) => { 390 console.info('upload task failed.'); 391 }; 392 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 393 task.on('failed', createOnCallback); 394 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 395 }).catch((err: BusinessError) => { 396 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 397 }); 398 ``` 399 400> **说明:** 401> 402> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 403 404### off('progress')<sup>10+</sup> 405 406off(event: 'progress', callback?: (progress: Progress) => void): void 407 408取消订阅前端任务进度事件。 409 410**系统能力**: SystemCapability.Request.FileTransferAgent 411 412**参数:** 413 414 | 参数名 | 类型 | 必填 | 说明 | 415 | -------- | -------- | -------- | -------- | 416 | event | string | 是 | 订阅的事件类型。<br>- 取值为'progress',表示任务进度。 | 417 | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 | 418 419**错误码:** 420 421以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 422 423 | 错误码ID | 错误信息 | 424 | -------- | -------- | 425 | 21900005 | task mode error. | 426 427**示例:** 428 429 ```ts 430 import { BusinessError, request } from '@kit.BasicServicesKit'; 431 432 let attachments: Array<request.agent.FormItem> = [{ 433 name: "taskOffTest", 434 value: { 435 filename: "taskOffTest.avi", 436 mimeType: "application/octet-stream", 437 path: "./taskOffTest.avi", 438 } 439 }]; 440 let config: request.agent.Config = { 441 action: request.agent.Action.UPLOAD, 442 url: 'http://127.0.0.1', 443 title: 'taskOffTest', 444 description: 'Sample code for event listening', 445 mode: request.agent.Mode.FOREGROUND, 446 overwrite: false, 447 method: "PUT", 448 data: attachments, 449 saveas: "./", 450 network: request.agent.Network.CELLULAR, 451 metered: false, 452 roaming: true, 453 retry: true, 454 redirect: true, 455 index: 0, 456 begins: 0, 457 ends: -1, 458 gauge: false, 459 precise: false, 460 token: "it is a secret" 461 }; 462 let createOffCallback1 = (progress: request.agent.Progress) => { 463 console.info('upload task progress.'); 464 }; 465 let createOffCallback2 = (progress: request.agent.Progress) => { 466 console.info('upload task progress.'); 467 }; 468 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 469 task.on('progress', createOffCallback1); 470 task.on('progress', createOffCallback2); 471 //表示取消createOffCallback1的订阅 472 task.off('progress', createOffCallback1); 473 //表示取消订阅前端任务进度的所有回调 474 task.off('progress'); 475 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 476 }).catch((err: BusinessError) => { 477 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 478 }); 479 ``` 480 481> **说明:** 482> 483> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 484 485### off('completed')<sup>10+</sup> 486 487off(event: 'completed', callback?: (progress: Progress) => void): void 488 489取消订阅前端任务完成事件。 490 491**系统能力**: SystemCapability.Request.FileTransferAgent 492 493**参数:** 494 495 | 参数名 | 类型 | 必填 | 说明 | 496 | -------- | -------- | -------- | -------- | 497 | event | string | 是 | 订阅的事件类型。<br>- 取值为'completed',表示任务完成。 | 498 | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 | 499 500**错误码:** 501 502以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 503 504 | 错误码ID | 错误信息 | 505 | -------- | -------- | 506 | 21900005 | task mode error. | 507 508**示例:** 509 510 ```ts 511 import { BusinessError, request } from '@kit.BasicServicesKit'; 512 513 let attachments: Array<request.agent.FormItem> = [{ 514 name: "taskOffTest", 515 value: { 516 filename: "taskOffTest.avi", 517 mimeType: "application/octet-stream", 518 path: "./taskOffTest.avi", 519 } 520 }]; 521 let config: request.agent.Config = { 522 action: request.agent.Action.UPLOAD, 523 url: 'http://127.0.0.1', 524 title: 'taskOffTest', 525 description: 'Sample code for event listening', 526 mode: request.agent.Mode.FOREGROUND, 527 overwrite: false, 528 method: "PUT", 529 data: attachments, 530 saveas: "./", 531 network: request.agent.Network.CELLULAR, 532 metered: false, 533 roaming: true, 534 retry: true, 535 redirect: true, 536 index: 0, 537 begins: 0, 538 ends: -1, 539 gauge: false, 540 precise: false, 541 token: "it is a secret" 542 }; 543 let createOffCallback1 = (progress: request.agent.Progress) => { 544 console.info('upload task completed.'); 545 }; 546 let createOffCallback2 = (progress: request.agent.Progress) => { 547 console.info('upload task completed.'); 548 }; 549 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 550 task.on('completed', createOffCallback1); 551 task.on('completed', createOffCallback2); 552 //表示取消createOffCallback1的订阅 553 task.off('completed', createOffCallback1); 554 //表示取消订阅前端任务完成的所有回调 555 task.off('completed'); 556 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 557 }).catch((err: BusinessError) => { 558 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 559 }); 560 ``` 561 562> **说明:** 563> 564> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 565 566### off('failed')<sup>10+</sup> 567 568off(event: 'failed', callback?: (progress: Progress) => void): void 569 570取消订阅前端任务失败事件。 571 572**系统能力**: SystemCapability.Request.FileTransferAgent 573 574**参数:** 575 576 | 参数名 | 类型 | 必填 | 说明 | 577 | -------- | -------- | -------- | -------- | 578 | event | string | 是 | 订阅的事件类型。<br>- 取值为'failed',表示任务失败。 | 579 | callback | function | 否 | 需要取消订阅的回调函数。若无此参数,则取消订阅当前类型的所有回调函数。 | 580 581**错误码:** 582 583以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 584 585 | 错误码ID | 错误信息 | 586 | -------- | -------- | 587 | 21900005 | task mode error. | 588 589**示例:** 590 591 ```ts 592 import { BusinessError, request } from '@kit.BasicServicesKit'; 593 594 let attachments: Array<request.agent.FormItem> = [{ 595 name: "taskOffTest", 596 value: { 597 filename: "taskOffTest.avi", 598 mimeType: "application/octet-stream", 599 path: "./taskOffTest.avi", 600 } 601 }]; 602 let config: request.agent.Config = { 603 action: request.agent.Action.UPLOAD, 604 url: 'http://127.0.0.1', 605 title: 'taskOffTest', 606 description: 'Sample code for event listening', 607 mode: request.agent.Mode.FOREGROUND, 608 overwrite: false, 609 method: "PUT", 610 data: attachments, 611 saveas: "./", 612 network: request.agent.Network.CELLULAR, 613 metered: false, 614 roaming: true, 615 retry: true, 616 redirect: true, 617 index: 0, 618 begins: 0, 619 ends: -1, 620 gauge: false, 621 precise: false, 622 token: "it is a secret" 623 }; 624 let createOffCallback1 = (progress: request.agent.Progress) => { 625 console.info('upload task failed.'); 626 }; 627 let createOffCallback2 = (progress: request.agent.Progress) => { 628 console.info('upload task failed.'); 629 }; 630 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 631 task.on('failed', createOffCallback1); 632 task.on('failed', createOffCallback2); 633 //表示取消createOffCallback1的订阅 634 task.off('failed', createOffCallback1); 635 //表示取消订阅前端任务失败的所有回调 636 task.off('failed'); 637 console.info(`Succeeded in creating a upload task. result: ${task.tid}`); 638 }).catch((err: BusinessError) => { 639 console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); 640 }); 641 ``` 642 643> **说明:** 644> 645> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 646 647### start<sup>10+</sup> 648 649start(callback: AsyncCallback<void>): void 650 651启动任务,无法启动已初始化的任务。使用callback异步回调。 652 653**需要权限**:ohos.permission.INTERNET 654 655**系统能力**: SystemCapability.Request.FileTransferAgent 656 657**参数:** 658 659 | 参数名 | 类型 | 必填 | 说明 | 660 | -------- | -------- | -------- | -------- | 661 | callback | function | 是 | 回调函数,开启任务成功,err为undefined,否则为错误对象。 | 662 663**错误码:** 664 665以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 666 667 | 错误码ID | 错误信息 | 668 | -------- | -------- | 669 | 13400003 | task service ability error. | 670 | 21900007 | task state error. | 671 672**示例:** 673 674 ```ts 675 import { BusinessError, request } from '@kit.BasicServicesKit'; 676 677 let config: request.agent.Config = { 678 action: request.agent.Action.DOWNLOAD, 679 url: 'http://127.0.0.1', 680 title: 'taskStartTest', 681 description: 'Sample code for start the download task', 682 mode: request.agent.Mode.BACKGROUND, 683 overwrite: false, 684 method: "GET", 685 data: "", 686 saveas: "./", 687 network: request.agent.Network.CELLULAR, 688 metered: false, 689 roaming: true, 690 retry: true, 691 redirect: true, 692 index: 0, 693 begins: 0, 694 ends: -1, 695 gauge: false, 696 precise: false, 697 token: "it is a secret" 698 }; 699 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 700 task.start((err: BusinessError) => { 701 if (err) { 702 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 703 return; 704 } 705 console.info(`Succeeded in starting a download task.`); 706 }); 707 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 708 }).catch((err: BusinessError) => { 709 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 710 }); 711 ``` 712 713> **说明:** 714> 715> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 716 717### start<sup>10+</sup> 718 719start(): Promise<void> 720 721启动任务,无法启动已初始化的任务。使用Promise异步回调。 722 723**需要权限**:ohos.permission.INTERNET 724 725**系统能力**: SystemCapability.Request.FileTransferAgent 726 727**返回值:** 728 729| 类型 | 说明 | 730| ------------------- | ------------------------- | 731| Promise<void> | Promise对象。无返回结果的Promise对象。 | 732 733**错误码:** 734 735以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 736 737 | 错误码ID | 错误信息 | 738 | -------- | -------- | 739 | 13400003 | task service ability error. | 740 | 21900007 | task state error. | 741 742**示例:** 743 744 ```ts 745 import { BusinessError, request } from '@kit.BasicServicesKit'; 746 747 let config: request.agent.Config = { 748 action: request.agent.Action.DOWNLOAD, 749 url: 'http://127.0.0.1', 750 title: 'taskStartTest', 751 description: 'Sample code for start the download task', 752 mode: request.agent.Mode.BACKGROUND, 753 overwrite: false, 754 method: "GET", 755 data: "", 756 saveas: "./", 757 network: request.agent.Network.CELLULAR, 758 metered: false, 759 roaming: true, 760 retry: true, 761 redirect: true, 762 index: 0, 763 begins: 0, 764 ends: -1, 765 gauge: false, 766 precise: false, 767 token: "it is a secret" 768 }; 769 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 770 task.start().then(() => { 771 console.info(`Succeeded in starting a download task.`); 772 }).catch((err: BusinessError) => { 773 console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 774 }); 775 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 776 }).catch((err: BusinessError) => { 777 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 778 }); 779 ``` 780 781> **说明:** 782> 783> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 784 785### stop<sup>10+</sup> 786 787stop(callback: AsyncCallback<void>): void 788 789停止任务,可以停止正在运行/正在等待/正在重试的任务。使用callback异步回调。 790 791**系统能力**: SystemCapability.Request.FileTransferAgent 792 793**参数:** 794 795 | 参数名 | 类型 | 必填 | 说明 | 796 | -------- | -------- | -------- | -------- | 797 | callback | function | 是 | 回调函数,停止任务成功,err为undefined,否则为错误对象 | 798 799**错误码:** 800 801以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 802 803 | 错误码ID | 错误信息 | 804 | -------- | -------- | 805 | 13400003 | task service ability error. | 806 | 21900007 | task state error. | 807 808**示例:** 809 810 ```ts 811 import { BusinessError, request } from '@kit.BasicServicesKit'; 812 813 let config: request.agent.Config = { 814 action: request.agent.Action.DOWNLOAD, 815 url: 'http://127.0.0.1', 816 title: 'taskStopTest', 817 description: 'Sample code for stop the download task', 818 mode: request.agent.Mode.BACKGROUND, 819 overwrite: false, 820 method: "GET", 821 data: "", 822 saveas: "./", 823 network: request.agent.Network.CELLULAR, 824 metered: false, 825 roaming: true, 826 retry: true, 827 redirect: true, 828 index: 0, 829 begins: 0, 830 ends: -1, 831 gauge: false, 832 precise: false, 833 token: "it is a secret" 834 }; 835 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 836 task.stop((err: BusinessError) => { 837 if (err) { 838 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 839 return; 840 } 841 console.info(`Succeeded in stopping a download task. `); 842 }); 843 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 844 }).catch((err: BusinessError) => { 845 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 846 }); 847 ``` 848 849 850### stop<sup>10+</sup> 851 852stop(): Promise<void> 853 854停止任务,可以停止正在运行/正在等待/正在重试的任务。使用Promise异步回调。 855 856**系统能力**: SystemCapability.Request.FileTransferAgent 857 858**返回值:** 859 860| 类型 | 说明 | 861| ------------------- | ------------------------- | 862| Promise<void> | Promise对象。无返回结果的Promise对象。 | 863 864**错误码:** 865 866以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 867 868 | 错误码ID | 错误信息 | 869 | -------- | -------- | 870 | 13400003 | task service ability error. | 871 | 21900007 | task state error. | 872 873**示例:** 874 875 ```ts 876 import { BusinessError, request } from '@kit.BasicServicesKit'; 877 878 let config: request.agent.Config = { 879 action: request.agent.Action.DOWNLOAD, 880 url: 'http://127.0.0.1', 881 title: 'taskStopTest', 882 description: 'Sample code for stop the download task', 883 mode: request.agent.Mode.BACKGROUND, 884 overwrite: false, 885 method: "GET", 886 data: "", 887 saveas: "./", 888 network: request.agent.Network.CELLULAR, 889 metered: false, 890 roaming: true, 891 retry: true, 892 redirect: true, 893 index: 0, 894 begins: 0, 895 ends: -1, 896 gauge: false, 897 precise: false, 898 token: "it is a secret" 899 }; 900 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 901 task.stop().then(() => { 902 console.info(`Succeeded in stopping a download task. `); 903 }).catch((err: BusinessError) => { 904 console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); 905 }); 906 console.info(`Succeeded in creating a download task. result: ${task.tid}`); 907 }).catch((err: BusinessError) => { 908 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 909 }); 910 ``` 911 912## request.agent.create<sup>10+</sup> 913 914create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void 915 916创建要上传或下载的任务,并将其排入队列,每个应用最多支持创建10个未完成的任务。使用callback异步回调。 917 918 919**需要权限**:ohos.permission.INTERNET 920 921**系统能力**: SystemCapability.Request.FileTransferAgent 922 923**参数:** 924 925 | 参数名 | 类型 | 必填 | 说明 | 926 | -------- | -------- | -------- | -------- | 927 | context | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 | 928 | config | [Config](#config10) | 是 | 上传/下载任务的配置信息。 | 929 | callback | AsyncCallback<[Task](#task10)> | 是 | 回调函数,返回创建任务的配置信息。 | 930 931**错误码:** 932 933以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 934 935 | 错误码ID | 错误信息 | 936 | -------- | -------- | 937 | 13400001 | file operation error. | 938 | 13400003 | task service ability error. | 939 | 21900004 | application task queue full error. | 940 | 21900005 | task mode error. | 941 942**示例:** 943 944 ```ts 945 import { BusinessError, request } from '@kit.BasicServicesKit'; 946 947 let attachments: Array<request.agent.FormItem> = [{ 948 name: "createTest", 949 value: { 950 filename: "createTest.avi", 951 mimeType: "application/octet-stream", 952 path: "./createTest.avi", 953 } 954 }]; 955 let config: request.agent.Config = { 956 action: request.agent.Action.UPLOAD, 957 url: 'http://127.0.0.1', 958 title: 'createTest', 959 description: 'Sample code for create task', 960 mode: request.agent.Mode.BACKGROUND, 961 overwrite: false, 962 method: "PUT", 963 data: attachments, 964 saveas: "./", 965 network: request.agent.Network.CELLULAR, 966 metered: false, 967 roaming: true, 968 retry: true, 969 redirect: true, 970 index: 0, 971 begins: 0, 972 ends: -1, 973 gauge: false, 974 precise: false, 975 token: "it is a secret" 976 }; 977 request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => { 978 if (err) { 979 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 980 return; 981 } 982 console.info(`Succeeded in creating a download task. result: ${task.config}`); 983 }); 984 ``` 985 986> **说明:** 987> 988> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 989 990## request.agent.create<sup>10+</sup> 991 992create(context: BaseContext, config: Config): Promise<Task> 993 994创建要上传或下载的任务,并将其排入队列,每个应用最多支持创建10个未完成的任务。使用Promise异步回调。 995 996 997**需要权限**:ohos.permission.INTERNET 998 999**系统能力**: SystemCapability.Request.FileTransferAgent 1000 1001**参数:** 1002 1003 | 参数名 | 类型 | 必填 | 说明 | 1004 | -------- | -------- | -------- | -------- | 1005 | context | [BaseContext](js-apis-inner-application-baseContext.md) | 是 | 基于应用程序的上下文。 | 1006 | config | [Config](#config10) | 是 | 上传/下载任务的配置信息。 | 1007 1008**返回值:** 1009 1010| 类型 | 说明 | 1011| ------------------- | ------------------------- | 1012| Promise<[Task](#task10)> | Promise对象。返回任务配置信息的Promise对象。 | 1013 1014**错误码:** 1015 1016以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 1017 1018 | 错误码ID | 错误信息 | 1019 | -------- | -------- | 1020 | 13400001 | file operation error. | 1021 | 13400003 | task service ability error. | 1022 | 21900004 | application task queue full error. | 1023 | 21900005 | task mode error. | 1024 1025**示例:** 1026 1027 ```ts 1028 import { BusinessError, request } from '@kit.BasicServicesKit'; 1029 1030 let attachments: Array<request.agent.FormItem> = [{ 1031 name: "createTest", 1032 value: { 1033 filename: "createTest.avi", 1034 mimeType: "application/octet-stream", 1035 path: "./createTest.avi", 1036 } 1037 }]; 1038 let config: request.agent.Config = { 1039 action: request.agent.Action.UPLOAD, 1040 url: 'http://127.0.0.1', 1041 title: 'createTest', 1042 description: 'Sample code for create task', 1043 mode: request.agent.Mode.BACKGROUND, 1044 overwrite: false, 1045 method: "PUT", 1046 data: attachments, 1047 saveas: "./", 1048 network: request.agent.Network.CELLULAR, 1049 metered: false, 1050 roaming: true, 1051 retry: true, 1052 redirect: true, 1053 index: 0, 1054 begins: 0, 1055 ends: -1, 1056 gauge: false, 1057 precise: false, 1058 token: "it is a secret" 1059 }; 1060 request.agent.create(getContext(), config).then((task: request.agent.Task) => { 1061 console.info(`Succeeded in creating a download task. result: ${task.config}`); 1062 }).catch((err) => { 1063 console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 1064 }); 1065 ``` 1066 1067> **说明:** 1068> 1069> 示例中context的获取方式请参见[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。 1070 1071## request.agent.remove<sup>10+</sup> 1072 1073remove(id: string, callback: AsyncCallback<void>): void 1074 1075移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止。使用callback异步回调。 1076 1077**系统能力**: SystemCapability.Request.FileTransferAgent 1078 1079**参数:** 1080 1081 | 参数名 | 类型 | 必填 | 说明 | 1082 | -------- | -------- | -------- | -------- | 1083 | id | string | 是 | 任务id。 | 1084 | callback | AsyncCallback<void> | 是 | 回调函数,删除指定任务成功,err为undefined,否则为错误对象。 | 1085 1086**错误码:** 1087 1088以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 1089 1090 | 错误码ID | 错误信息 | 1091 | -------- | -------- | 1092 | 13400003 | task service ability error. | 1093 | 21900006 | task not found error. | 1094 1095**示例:** 1096 1097 ```ts 1098 import { BusinessError, request } from '@kit.BasicServicesKit'; 1099 1100 request.agent.remove("123456", (err: BusinessError) => { 1101 if (err) { 1102 console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`); 1103 return; 1104 } 1105 console.info(`Succeeded in creating a download task.`); 1106 }); 1107 ``` 1108 1109 1110## request.agent.remove<sup>10+</sup> 1111 1112remove(id: string): Promise<void> 1113 1114移除属于调用方的指定任务,如果正在处理中,该任务将被迫停止,使用Promise异步回调。 1115 1116**系统能力**: SystemCapability.Request.FileTransferAgent 1117 1118**参数:** 1119 1120 | 参数名 | 类型 | 必填 | 说明 | 1121 | -------- | -------- | -------- | -------- | 1122 | id | string | 是 | 任务id。 | 1123 1124**返回值:** 1125 1126| 类型 | 说明 | 1127| ------------------- | ------------------------- | 1128| Promise<void> | Promise对象。无返回结果的Promise对象。 | 1129 1130**错误码:** 1131 1132以下错误码的详细介绍请参见[上传下载错误码](../apis-basic-services-kit/errorcode-request.md)。 1133 1134 | 错误码ID | 错误信息 | 1135 | -------- | -------- | 1136 | 13400003 | task service ability error. | 1137 | 21900006 | task not found error. | 1138 1139**示例:** 1140 1141 ```ts 1142 import { BusinessError, request } from '@kit.BasicServicesKit'; 1143 1144 request.agent.remove("123456").then(() => { 1145 console.info(`Succeeded in removing a download task. `); 1146 }).catch((err: BusinessError) => { 1147 console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); 1148 }); 1149 ``` 1150 1151<!--no_check-->