imageBuffer: ArrayBuffer如何转成Uri去上传文件 - HarmonyOS 鸿蒙Next

imageBuffer: ArrayBuffer如何转成Uri去上传文件 - HarmonyOS 鸿蒙Next

### 设备信息
- **Mate60**
- **API版本**: Api13
- **DevEco Studio版本**: 5.0.7.200

**问题描述**:
imageBuffer: ArrayBuffer如何转成Uri去上传文件 我这边用了图片压缩,压缩之后获取到imageBuffer: ArrayBuffer,但是上传文件要用uri,imageBuffer如何转成Uri呢?

```javascript
let newPath = context.cacheDir + `/select.png`;
// 图片压缩
const imageSourceApi: image.ImageSource = image.createImageSource(newPath);
let packOpts: image.PackingOption = {
  format: "image/jpeg", quality: 98
}
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(imageSourceApi, packOpts)
  .then(async (imageBuffer: ArrayBuffer) => {
    // 这里怎么转成Uri上传文件呢?
    console.info('Succeeded in packing the image.');
  }).catch((error: BusinessError) => {
  console.error(`Failed to pack the image.code ${error.code},message is ${error.message}`);
})

更多关于imageBuffer: ArrayBuffer如何转成Uri去上传文件 - HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

可以将图片保存到沙箱,沙箱路径可通过fileUri.getUriFromPath方法获取文件URI

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V14/js-apis-file-fileuri-V14#fileurigeturifrompath

更多关于imageBuffer: ArrayBuffer如何转成Uri去上传文件 - HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙系统中,imageBuffer: ArrayBuffer可以通过FileUri类进行转换并上传文件。首先,使用File类将ArrayBuffer转换为文件对象,然后通过Uri类生成对应的URI。具体步骤如下:

  1. ArrayBuffer转换为Uint8Array

    const uint8Array = new Uint8Array(imageBuffer);
    
  2. 使用File类创建文件对象:

    const file = new File([uint8Array], 'image.png', { type: 'image/png' });
    
  3. 通过Uri类生成文件的URI:

    const uri = Uri.fromFile(file);
    
  4. 上传文件时,直接使用生成的uri进行上传操作。

以上步骤实现了从ArrayBufferUri的转换,适用于鸿蒙系统中文件上传的场景。

回到顶部