鸿蒙Next中如何通过API请求下载文件

在鸿蒙Next开发中,我想通过API实现文件下载功能,但不太清楚具体的实现步骤。请问应该如何正确调用相关API?能否提供一个完整的代码示例,包括请求发送、文件存储和错误处理等关键环节?另外需要注意哪些权限配置和兼容性问题?

2 回复

在鸿蒙Next中,可通过@ohos.net.http模块实现文件下载:

  1. 创建HttpRequest对象:
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
  1. 发起请求并获取文件数据:
let url = 'https://example.com/file.zip';
httpRequest.request(url, {
  method: http.RequestMethod.GET,
  responseType: http.ResponseType.ARRAY_BUFFER // 重要:指定二进制数据
}, (err, data) => {
  if (!err) {
    // data.result为ArrayBuffer类型文件数据
    this.saveFile(data.result);
  }
});
  1. 保存文件到本地:
import fileio from '@ohos.fileio';
async saveFile(arrayBuffer) {
  let filePath = '本地存储路径/file.zip';
  let fd = fileio.openSync(filePath, 0o102, 0o666);
  fileio.writeSync(fd, arrayBuffer);
  fileio.closeSync(fd);
}

注意:

  • 需要申请网络权限:ohos.permission.INTERNET
  • 大文件建议使用流式下载
  • 实际路径需使用正确的沙箱路径

核心就是通过http模块获取二进制数据,再用文件API写入本地。

更多关于鸿蒙Next中如何通过API请求下载文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next中,可以通过@ohos.net.http模块的HTTP API实现文件下载。以下是核心步骤和示例代码:

主要步骤:

  1. 创建HTTP请求:使用createHttp()方法初始化请求对象。
  2. 配置请求参数:设置URL、请求方法(GET)、响应类型(数组缓冲区)等。
  3. 发起请求并处理响应:通过request()方法发送请求,将返回的数组缓冲区数据写入文件。

示例代码:

import http from '@ohos.net.http';
import fs from '@ohos.file.fs';

async function downloadFile(url: string, savePath: string) {
  // 1. 创建HTTP请求
  let httpRequest = http.createHttp();
  
  try {
    // 2. 发起请求
    let response = await httpRequest.request(
      url,
      {
        method: http.RequestMethod.GET,
        responseType: http.ResponseType.ARRAY_BUFFER // 关键:指定响应类型为二进制
      }
    );

    // 3. 检查响应状态
    if (response.responseCode === http.ResponseCode.OK) {
      // 4. 获取二进制数据
      let buffer = response.result as ArrayBuffer;
      
      // 5. 写入文件
      let file = fs.openSync(savePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
      fs.writeSync(file.fd, buffer);
      fs.closeSync(file);
      
      console.log('文件下载成功:', savePath);
    } else {
      console.error('下载失败,状态码:', response.responseCode);
    }
  } catch (error) {
    console.error('请求异常:', error);
  } finally {
    // 6. 释放请求对象
    httpRequest.destroy();
  }
}

// 使用示例
let fileUrl = 'https://example.com/file.zip';
let localPath = '/data/storage/el2/base/files/downloaded_file.zip'; // 应用沙箱路径
downloadFile(fileUrl, localPath);

关键说明:

  • 权限配置:在module.json5中声明网络权限:
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
    
  • 路径注意:保存路径需使用应用沙箱路径(如/data/storage/el2/base/files/)。
  • 响应类型:必须设置为ARRAY_BUFFER才能正确处理二进制文件数据。
  • 错误处理:务必添加try-catch和响应状态码检查。

此方法适用于下载图片、文档、压缩包等任意文件类型。

回到顶部