鸿蒙NEXT使用request模块实现本地文件上传 原创

威哥爱编程
发布于 2025-1-7 16:48
1.2w浏览
0收藏

大家好,我是 V 哥。在鸿蒙 NEXT API 12 中,可以使用 ​​ohos.request​​​ 模块提供的上传接口将本地文件上传到服务器。自定义代理设置可以通过 ​​request.agent.create​​ 接口来实现,从而指定代理服务器的地址。下面是一个详细的案例代码,演示了如何使用自定义代理上传本地文件。整理好的学习笔记,分享给大家。

示例代码

import { request } from '@ohos.request';
import { Log } from '@ohos.logger';
import fs from '@ohos.fileSystem';

export default {
  data: {
    localFilePath: '/data/files/example.txt', // 需要上传的文件路径
    serverUrl: 'https://example.com/upload', // 上传文件的服务器URL
    proxyUrl: 'http://proxy.example.com:8080', // 自定义代理地址
  },

  onInit() {
    // 在组件初始化时,触发上传文件的操作
    this.uploadFileWithProxy();
  },

  async uploadFileWithProxy() {
    try {
      // 创建代理代理服务
      const agent = await request.agent.create({
        proxy: this.proxyUrl, // 设置自定义代理地址
      });
      Log.info('Custom proxy agent created successfully.');

      // 读取本地文件
      const fileData = await this.readFile(this.data.localFilePath);
      if (!fileData) {
        Log.error('Failed to read local file.');
        return;
      }

      // 准备上传请求的参数
      const options = {
        url: this.data.serverUrl, // 目标上传URL
        method: 'POST', // HTTP方法为POST
        headers: {
          'Content-Type': 'multipart/form-data', // 设置请求头
        },
        data: {
          file: fileData, // 上传的文件内容
        },
        agent, // 使用代理
      };

      // 发起文件上传请求
      const response = await request.upload(options);
      if (response && response.status === 200) {
        Log.info('File uploaded successfully: ' + JSON.stringify(response));
      } else {
        Log.error('File upload failed: ' + JSON.stringify(response));
      }
    } catch (error) {
      Log.error('Error during file upload: ' + error.message);
    }
  },

  // 读取本地文件内容的函数
  async readFile(filePath: string) {
    try {
      // 读取本地文件
      const fileStats = await fs.stat(filePath);
      if (!fileStats || !fileStats.isFile) {
        return null; // 文件不存在或不是一个文件
      }

      const fileData = await fs.readFile(filePath);
      return fileData;
    } catch (error) {
      Log.error('Error reading file: ' + error.message);
      return null;
    }
  },
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.

解释:

  1. 代理服务创建 (request.agent.create​)
  • 在​​uploadFileWithProxy​​ 函数中,我们使用​​request.agent.create​​ 创建了一个自定义代理服务,代理地址由​​proxyUrl​​ 提供。
  • 该服务用于通过代理上传文件。
  1. 读取本地文件
  • ​readFile​​ 函数读取本地文件内容。在这个示例中,我们假设上传的是一个文本文件。
  • 使用​​fs.stat​​ 检查文件是否存在,​​fs.readFile​​ 获取文件内容。
  1. 上传文件
  • 使用​​request.upload​​ 发起文件上传请求,并且指定代理。
  • ​options​​ 中的​​url​​ 为目标上传地址,​​method​​ 为 HTTP 请求方法(在此为​​POST​​)。
  • 上传文件的数据作为​​data​​ 部分传递给服务器。
  1. 日志
  • 使用​​Log​​ 模块打印上传过程的相关日志信息,帮助调试和监控。

需要注意:

  • ​request.upload​​ 方法是鸿蒙系统提供的用于上传文件的接口。确保传递正确的 options,包括文件内容、上传URL等。
  • 代理的地址通过request.agent.create 设置,可以为HTTP请求指定一个中间代理服务器,尤其在网络受限或者有特殊需求时非常有用。
  • 需要正确配置服务器端接收文件的接口(如POST 方法和表单数据处理)。
  • 将需要上传的文件路径替换为你本地实际存在的文件路径(如/data/files/example.txt)。
  • 确保服务器端能够处理来自代理服务器的上传请求。
  • 使用合适的proxyUrl 进行自定义代理。

此示例提供了一个基础框架,你可以根据实际需求扩展或修改功能,感谢支持,关注威哥爱编程,一起学鸿蒙开发。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报


回复
    相关推荐