Upload Files with a Custom Proxy in HarmonyOS Using ohos.request

This guide demonstrates how to use the ohos.request module in HarmonyOS NEXT API 12 to upload a local file through a custom proxy by creating a proxy agent, reading the file, configuring request options, and handling responses and errors.

Java Architecture Stack
Java Architecture Stack
Java Architecture Stack
Upload Files with a Custom Proxy in HarmonyOS Using ohos.request

In HarmonyOS NEXT API 12, the ohos.request module provides an upload interface that can send local files to a server. By creating a custom proxy with request.agent.create, you can route the upload through a specified proxy server.

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

export default {
  data: {
    localFilePath: '/data/files/example.txt', // path of the file to upload
    serverUrl: 'https://example.com/upload', // server upload URL
    proxyUrl: 'http://proxy.example.com:8080' // custom proxy address
  },
  onInit() {
    this.uploadFileWithProxy();
  },
  async uploadFileWithProxy() {
    try {
      // Create proxy agent
      const agent = await request.agent.create({ proxy: this.proxyUrl });
      Log.info('Custom proxy agent created successfully.');

      // Read local file
      const fileData = await this.readFile(this.data.localFilePath);
      if (!fileData) {
        Log.error('Failed to read local file.');
        return;
      }

      // Prepare upload request options
      const options = {
        url: this.data.serverUrl,
        method: 'POST',
        headers: { 'Content-Type': 'multipart/form-data' },
        data: { file: fileData },
        agent
      };

      // Send upload request
      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) {
    try {
      const fileStats = await fs.stat(filePath);
      if (!fileStats || !fileStats.isFile) {
        return null; // file does not exist or is not a file
      }
      const fileData = await fs.readFile(filePath);
      return fileData;
    } catch (error) {
      Log.error('Error reading file: ' + error.message);
      return null;
    }
  }
};

Explanation

Proxy service creation : In uploadFileWithProxy, request.agent.create creates a custom proxy agent using the address defined in proxyUrl. The agent is then attached to the upload request.

The proxy allows the file to be sent through an intermediate server, useful in restricted networks.

Read local file : The readFile function checks the file existence with fs.stat and reads its content with fs.readFile. It returns the file data or null if the file cannot be accessed.

Upload file : request.upload is called with an options object that includes: url: target upload address. method: HTTP method, set to POST. headers: content type set to multipart/form-data. data: the file content. agent: the custom proxy agent.

The response is logged; a status of 200 indicates success.

Logging : The Log module records each step, helping with debugging and monitoring.

Important Notes

Ensure the options object passed to request.upload contains correct file data, URL, and other parameters.

The proxy address is set via request.agent.create; this is useful when network restrictions require a middle proxy.

The server must implement a POST endpoint capable of handling multipart form data.

Replace the placeholder file path with an actual existing file on your device.

Make sure the server can accept requests coming from the proxy.

Provide a valid proxyUrl that matches your proxy configuration.

mobile developmentHarmonyOSFile UploadNetwork RequestCustom Proxyohos.request
Java Architecture Stack
Written by

Java Architecture Stack

Dedicated to original, practical tech insights—from skill advancement to architecture, front‑end to back‑end, the full‑stack path, with Wei Ge guiding you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.