HarmonyOS 鸿蒙Next中如何将resources->media文件夹下的图片进行图片上传

HarmonyOS 鸿蒙Next中如何将resources->media文件夹下的图片进行图片上传

10 回复

1、在HSP模块中获取并展示entry模块的resources/media中的图片资源,示例代码如下:

import { application, common } from "@kit.AbilityKit";
import { image } from "@kit.ImageKit";
import { BusinessError } from "@kit.BasicServicesKit";

@Component
export struct MainPage {
  @State image: PixelMap | undefined = undefined; // 创建PixelMap状态变量。

  async getFile() {
    let buf: ArrayBuffer | undefined
    try {
      const context = this.getUIContext().getHostContext() as common.UIAbilityContext
      application.createModuleContext(context, 'entry').then((data) => {
        data.resourceManager.getMediaByName('startIcon', (error: BusinessError, value: Uint8Array) => {
          if (error != null) {
            console.error("error is " + JSON.stringify(error));
          } else {
            buf = value.buffer as ArrayBuffer
            let imageSource: image.ImageSource = image.createImageSource(buf);
            let options: image.DecodingOptions = {
              'desiredPixelFormat': image.PixelMapFormat.RGBA_8888,
            };
            imageSource.createPixelMap(options).then((pixelMap: PixelMap) => {
              this.image = pixelMap;
            });
          }
        });
      })
    } catch (error) {
      console.error("Failed to get ArrayBuffer");
    }
  }
  build() {
    Column({space: 20}) {
      Text('跨模块获取资源')
      Button('HSP模块获取HAP模块中resources下的media媒体资源')
        .onClick(() => {
          this.getFile()
        })
      Image(this.image).width('50%')
    }
    .width('100%')
    .height('100%')
  }
}

2、 上传图片可以参考官网文档:上传应用文件。其中request.uploadFile方式仅支持上传应用缓存文件路径(cacheDir)下的文件,request.agent方式支持上传用户公共文件和应用缓存文件路径下的文件。

更多关于HarmonyOS 鸿蒙Next中如何将resources->media文件夹下的图片进行图片上传的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


当前代码块,在非EntryAbility下,一直拿不到value

const context = this.getUIContext().getHostContext() as common.UIAbilityContext
    context.resourceManager.getMediaContent($r('app.media.logo').id,
      (error: BusinessError, value: Uint8Array) => {
        if (error != null) {
          console.error("error is " + error);
        } else {
          buffer = value.buffer as ArrayBuffer
        }
      });

非entry模块,当前在mine模块HSP包

资源转二进制数据 使用resourceManager将图片资源解码为ArrayBuffer

写入沙箱临时文件 将二进制数据写入应用沙箱目录,生成可访问的文件路径

构建上传参数 使用FormData包装文件数据

发起网络请求 通过HTTP库(如Axios)上传文件

怎么获取resources->media文件夹下的图片对应的filePath路径

可以考虑将图片拷贝进沙箱,再使用沙箱路径。

context.resourceManager.getMediaContent($r('app.media.startIcon')
context.resourceManager.getMediaContent($r('app.media.startIcon').id,
  (error: BusinessError, value: Uint8Array) => {
    if (error != null) {
      console.error("error is " + error);
    } else {
      this.uploadImage(value.buffer as ArrayBuffer)
    }
  });

在HarmonyOS Next中,通过PhotoAccessHelper模块访问media资源。使用getPhotoAccessHelper()获取助手实例,调用createAsset()方法创建资源选择器。通过PhotoViewPicker选择指定路径下的图片文件,获取其URI后使用@ohos.request上传模块的uploadTask()方法提交至服务器。需在module.json5中声明ohos.permission.READ_IMAGEVIDEO权限,并动态申请存储访问权限。

在HarmonyOS Next中,resources/media目录下的图片属于应用资源文件,无法直接通过常规的文件路径访问进行上传操作。以下是两种推荐方案:

  1. 资源ID方式读取转字节流
    通过资源管理器获取图片数据:
import resourceManager from '@ohos.resourceManager';

// 获取资源描述符
let resource = await resourceManager.getRawFile('image_name.jpg');
// 转换为ArrayBuffer用于上传
let buffer = await resource.read();
  1. 资源文件预置到沙箱路径
    启动时将需上传的图片复制到应用沙箱目录:
import fs from '@ohos.file.fs';

// 从rawfile复制到沙箱
let rawFileFd = await resourceManager.getRawFd('image_name.jpg');
let sandboxPath = context.filesDir + '/upload_images/image.jpg';
fs.copyFile(rawFileFd.fd, sandboxPath);

注意事项:

  • 需在module.json5中声明存储权限:ohos.permission.READ_MEDIA
  • 大文件建议使用分段上传
  • 实际路径需根据工程结构调整rawfile路径

推荐使用第一种方案直接操作资源数据流,避免产生临时文件。

回到顶部