基于request上传下载控制

HarmonyOS官方账号
发布于 2024-10-8 09:19
浏览
0收藏

​request主要给应用提供上传下载文件、后台传输代理的基础能力。

场景一:上传下载进度回调。

方式一:使用request.agent.create下载文件开启进度回调,当前规格是约1s一次回调。

//进度回调的Callback 
let progressCallback = (progress: request.agent.Progress) => { 
  console.info('download task progress:'+progress.sizes+'/'+progress.processed);  }; 
request.agent.create(context, config1).then((task: request.agent.Task) => { 
  console.log(task.tid) 
  //开启进度回调监听 
  task.on('progress', progressCallback); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
  task.on('completed', createOnCallback); 
  task.start((err: BusinessError) => { 
    if (err) { 
      console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 
      return; 
    } 
    console.info(`Succeeded in starting a download task.`); 
  }); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
}).catch((err: BusinessError) => { 
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 
});

方式二:使用request.downloadFile下载文件,传入context和DownloadConfig,开启进度回调。

request.downloadFile(context.getApplicationContext(), { 
  url: 'xxxxx', 
  filePath: filesDir + '/文件路径', 
  enableMetered: true 
}).then((downloadTask: request.DownloadTask) => { 
  let progresCallback = (receivedSize: number, totalSize: number) => { 
    console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); 
  }; 
  //开启进度回调 
  downloadTask.on('progress', progresCallback); 
})

场景二:暂停恢复下载。

要实现按钮点击暂停/恢复下载,需要先将Task传入,然后调用pause()暂停/resume()恢复下载任务。

request.agent.create(getContext(), config).then((task: request.agent.Task) => { 
  // pause暂停任务 
  task.pause((err: BusinessError) => { 
    if (err) { 
      console.error(`Failed to pause the download task, Code: ${err.code}, message:    ${err.message}`); 
      return; 
    } 
    console.info(`Succeeded in pausing a download task. `); 
  }); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
}).catch((err: BusinessError) => { 
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 
});
request.agent.create(getContext(), config).then((task: request.agent.Task) => { 
  // resume恢复下载任务 
  task.resume((err: BusinessError) => { 
    if (err) { 
      console.error(`Failed to resume the download task, Code: ${err.code}, message:   ${err.message}`); 
      return; 
    } 
    console.info(`Succeeded in resuming a download task. `); 
  }); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
}).catch((err: BusinessError) => { 
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 
});

场景三:后台上传下载,应用长时任务。

requestdownload接口默认是后台任务,支持应用长时任务。

request.agent需要配置为BACKGROUND模式,后台任务默认会有系统通知。

gauge:后台任务的过程进度通知策略,仅应用于后台任务,默认值为false。

  • false:代表仅完成或失败的通知。
  • true:发出每个进度,已完成或失败的通知。

上传任务配置:

let attachments: Array<request.agent.FormItem> = [{ 
  name: "createTest", 
  value: { 
    filename: "createTest.mp4", 
    mimeType: "application/octet-stream", 
    path: "./createTest.mp4", 
  } 
}]; 
let config: request.agent.Config = { 
  //任务操作选项。UPLOAD表示上传任务。DOWNLOAD表示下载任务。 
  action: request.agent.Action.UPLOAD, 
  url: 'http://127.0.0.1', 
  title: 'createTest', 
  description: 'Sample code for create task', 
  //下载的模式,FOREGROUND表示前台任务;BACKGROUND表示后台任务。 
  mode: request.agent.Mode.BACKGROUND, 
  //覆写配置true,覆盖已存在的文件。 false,下载失败。 
  overwrite: false, 
  method: "PUT", 
  data: attachments, 
  saveas: "./", 
  network: request.agent.Network.CELLULAR, 
  //是否允许在按流量计费的网络中工作,默认为false。 
  metered: false, 
  roaming: true, 
  //是否为后台任务启用自动重试,仅应用于后台任务,默认为true。 
  retry: true, 
  //是否允许重定向,默认为true。 
  redirect: true, 
  index: 0, 
  gauge: true, 
  //如果设置为true,在上传/下载无法获取文件大小时任务失败。 
  precise: false, 
  token: "it is a secret", 
  //任务的优先级。任务模式相同的情况下,该配置项的数字越小优先级越高,默认值为0。 
  priority:0 
}; 
request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => { 
  if (err) { 
    console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 
    return; 
  } 
  console.info(`Succeeded in creating a download task. result: ${task.config}`); 
});

下载任务配置:

let config1: request.agent.Config  =  { 
  action: request.agent.Action.DOWNLOAD, 
  url: "https://fe-static.xhscdn.com/mp/red/bc446184a0c84aa785ea3cada920f6ac.zip", 
  overwrite: true, 
  method: 'GET', 
  //保存的地址,默认为cache目录下,如果需要保存在子目录下需要提前手动创建。 
  saveas: './', 
  mode: request.agent.Mode.BACKGROUND, 
  gauge: true, 
  priority:0 
} 
let createOnCallback2 = (progress: request.agent.Progress) => { 
  console.info('download task pro.'+progress.sizes+'/'+progress.processed); 
}; 
let createOnCallback = (progress: request.agent.Progress) => { 
 
  console.info('downloadTask complete,filesDir:' ); 
 
}; 
let createOnCallback1 = (progress: request.agent.Progress) => { 
  console.info('download task failed.'+progress); 
}; 
request.agent.create(context, config1).then((task: request.agent.Task) => { 
  console.log(task.tid) 
  task.on('progress', createOnCallback2); 
  task.on('failed', createOnCallback1); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
  task.on('completed', createOnCallback); 
  task.start((err: BusinessError) => { 
    if (err) { 
      console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); 
      return; 
    } 
    console.info(`Succeeded in starting a download task.`); 
  }); 
  console.info(`Succeeded in creating a download task. result: ${task.tid}`); 
}).catch((err: BusinessError) => { 
  console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); 
});

场景四:断点续传。

断点续传的场景,如果是因网络等问题导致的任务失败,用户可以改为使用api10后台任务设置retry属性为true,这样内部会有自动暂停,网络恢复时自动重试,内部能续传时自动续传。on('pause') 回调会监听到它的暂停状态。

场景五:获取服务端返回的headers信息,用于后续处理。

订阅on('response')事件返回的headers中包含有header和body,可以通过解析返回的headers来进行后续处理。

let responseCallback = (response: request.agent.HttpResponse) => { 
  console.info('download task response.'+JSON.stringify(response)+JSON.stringify(response.headers)); 
}; 
task.on('response',responseCallback)


分类
1
收藏
回复
举报
回复
    相关推荐