当前位置:   article > 正文

【HarmonyOS NEXT】鸿蒙应用文件上传下载(ohos.request)_鸿蒙request.uploadfile

鸿蒙request.uploadfile

应用可以将应用文件上传到网络服务器,也可以从网络服务器下载网络资源文件到本地应用文件目录。

上传应用文件

开发者可以使用上传下载模块(ohos.request)的上传接口将本地文件上传。文件上传过程使用系统服务代理完成, 在api12中request.agent.create接口增加了设置代理地址参数,支持用户设置自定义代理地址。

说明

当前上传应用文件功能,仅支持上传应用缓存文件路径(cacheDir)下的文件。

使用上传下载模块,需声明权限
:ohos.permission.INTERNET。

以下示例代码演示两种将应用缓存文件路径下的文件上传至网络服务器的方式:

  1. // 方式一:request.uploadFile
  2. // pages/xxx.ets
  3. import common from '@ohos.app.ability.common';
  4. import fs from '@ohos.file.fs';
  5. import request from '@ohos.request';
  6. import { BusinessError } from '@ohos.base';
  7. // 获取应用文件路径
  8. let context = getContext(this) as common.UIAbilityContext;
  9. let cacheDir = context.cacheDir;
  10. // 新建一个本地应用文件
  11. let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  12. fs.writeSync(file.fd, 'upload file test');
  13. fs.closeSync(file);
  14. // 上传任务配置项
  15. let header = new Map<Object, string>();
  16. header.set('key1', 'value1');
  17. header.set('key2', 'value2');
  18. let files: Array<request.File> = [
  19. //uri前缀internal://cache 对应cacheDir目录
  20. { filename: 'test.txt', name: 'test', uri: 'internal://cache/test.txt', type: 'txt' }
  21. ]
  22. let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
  23. let uploadConfig: request.UploadConfig = {
  24. url: 'https://xxx',
  25. header: header,
  26. method: 'POST',
  27. files: files,
  28. data: data
  29. }
  30. // 将本地应用文件上传至网络服务器
  31. try {
  32. request.uploadFile(context, uploadConfig)
  33. .then((uploadTask: request.UploadTask) => {
  34. uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
  35. for (let i = 0; i < taskStates.length; i++) {
  36. console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
  37. }
  38. });
  39. })
  40. .catch((err: BusinessError) => {
  41. console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
  42. })
  43. } catch (error) {
  44. let err: BusinessError = error as BusinessError;
  45. console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
  46. }
  1. // 方式二:request.agent
  2. // 获取应用文件路径
  3. let context = getContext(this) as common.UIAbilityContext;
  4. let cacheDir = context.cacheDir;
  5. // 新建一个本地应用文件
  6. let file = fs.openSync(cacheDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  7. fs.writeSync(file.fd, 'upload file test');
  8. fs.closeSync(file);
  9. let attachments: Array<request.agent.FormItem> = [{
  10. name: "test",
  11. value: [
  12. {
  13. filename: "test.txt",
  14. path: "./test.txt",
  15. },
  16. ]
  17. }];
  18. let config: request.agent.Config = {
  19. action: request.agent.Action.UPLOAD,
  20. url: 'http://xxx',
  21. mode: request.agent.Mode.FOREGROUND,
  22. overwrite: true,
  23. method: "POST",
  24. data: attachments,
  25. saveas: "./"
  26. };
  27. request.agent.create(getContext(), config).then((task: request.agent.Task) => {
  28. task.start((err: BusinessError) => {
  29. if (err) {
  30. this.progress = `Failed to start the upload task, Code: ${err.code} message: ${err.message}`;
  31. return;
  32. }
  33. });
  34. task.on('progress', async(progress) => {
  35. console.warn(`/Request upload status ${progress.state}, uploaded ${progress.processed}`);
  36. })
  37. task.on('completed', async() => {
  38. console.warn(`/Request upload completed`);
  39. })
  40. }).catch((err: BusinessError) => {
  41. this.progress = `Failed to create a upload task, Code: ${err.code}, message: ${err.message}`;
  42. });

下载网络资源文件至应用文件目录

开发者可以使用上传下载模块(ohos.request)的下载接口将网络资源文件下载到应用文件目录。对已下载的网络资源文件,开发者可以使用基础文件IO接口(ohos.file.fs)对其进行访问,使用方式与应用文件访问一致。文件下载过程使用系统服务代理完成, 在api12中request.agent.create接口增加了设置代理地址参数,支持用户设置自定义代理地址。

说明

当前网络资源文件仅支持下载至应用文件目录。

使用上传下载模块,需声明权限:ohos.permission.INTERNET。

以下示例代码演示两种将网络资源文件下载到应用文件目录的方式:

  1. // 方式一:request.downloadFile
  2. // pages/xxx.ets
  3. // 将网络资源文件下载到应用文件目录并读取一段内容
  4. import common from '@ohos.app.ability.common';
  5. import fs from '@ohos.file.fs';
  6. import request from '@ohos.request';
  7. import { BusinessError } from '@ohos.base';
  8. import buffer from '@ohos.buffer';
  9. // 获取应用文件路径
  10. let context = getContext(this) as common.UIAbilityContext;
  11. let filesDir = context.filesDir;
  12. try {
  13. request.downloadFile(context, {
  14. url: 'https://xxxx/xxxx.txt',
  15. filePath: filesDir + '/xxxx.txt'
  16. }).then((downloadTask: request.DownloadTask) => {
  17. downloadTask.on('complete', () => {
  18. console.info('download complete');
  19. let file = fs.openSync(filesDir + '/xxxx.txt', fs.OpenMode.READ_WRITE);
  20. let arrayBuffer = new ArrayBuffer(1024);
  21. let readLen = fs.readSync(file.fd, arrayBuffer);
  22. let buf = buffer.from(arrayBuffer, 0, readLen);
  23. console.info(`The content of file: ${buf.toString()}`);
  24. fs.closeSync(file);
  25. })
  26. }).catch((err: BusinessError) => {
  27. console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
  28. });
  29. } catch (error) {
  30. let err: BusinessError = error as BusinessError;
  31. console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
  32. }
  1. // 方式二:request.agent
  2. // pages/xxx.ets
  3. // 将网络资源文件下载到应用文件目录并读取一段内容
  4. import common from '@ohos.app.ability.common';
  5. import fs from '@ohos.file.fs';
  6. import request from '@ohos.request';
  7. import { BusinessError } from '@ohos.base';
  8. import buffer from '@ohos.buffer';
  9. let config: request.agent.Config = {
  10. action: request.agent.Action.DOWNLOAD,
  11. url: 'https://xxxx/test.txt',
  12. gauge: true,
  13. overwrite: true,
  14. network: request.agent.Network.WIFI,
  15. };
  16. request.agent.create(getContext(), config).then((task: request.agent.Task) => {
  17. task.start((err: BusinessError) => {
  18. if (err) {
  19. this.progress = `Failed to start the upload task, Code: ${err.code} message: ${err.message}`;
  20. return;
  21. }
  22. });
  23. task.on('progress', async(progress) => {
  24. console.warn(`/Request download status ${progress.state}, downloaded ${progress.processed}`);
  25. })
  26. task.on('completed', async() => {
  27. console.warn(`/Request download completed`);
  28. })
  29. }).catch((err: BusinessError) => {
  30. this.progress = `Failed to create a download task, Code: ${err.code}, message: ${err.message}`;
  31. });

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/976765
推荐阅读
相关标签
  

闽ICP备14008679号