HarmonyOS 鸿蒙Next Uri 问题

HarmonyOS 鸿蒙Next Uri 问题

Web 中通过onShowFileSelector 调用原生图片选择器。选择图片后回传给 H5。
使用 PhotoViewPicker 选择图片后,不做任何处理,回调给 H5,其能正常收到数据并展示,因为选择后返回的数据是一个 uri。
问题:
如果进行图片压缩,并将压缩后的图片的path转换为 uri(通过 fileuri.getUriFromPath 方法),则 H5 无法收到数据并展示。压缩后的图片是真实存在的。

那我要怎么编写这个 uri 呢


更多关于HarmonyOS 鸿蒙Next Uri 问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

你参考一下:

【index.ets】

import web_webview from '@ohos.web.webview'

import picker from '@ohos.file.picker'

import { BusinessError } from '@ohos.base'

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

import { hilog } from '@kit.PerformanceAnalysisKit'

import { image } from '@kit.ImageKit';

import { util } from '@kit.ArkTS';

@Entry
@Component
struct IndexPage {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  baseDirStr: string = "/soon"
  imageDirStr: string = "/images"

  aboutToAppear(): void {

    web_webview.WebviewController.setWebDebuggingAccess(true)

  }

  getBaseFileDir() {

    let path = getContext().filesDir + this.baseDirStr

    if (fs.accessSync(path) == false) {

      fs.mkdirSync(path)

    }

    return path

  }

  getImageFileDir() {

    let path = this.getBaseFileDir() + this.imageDirStr

    if (fs.accessSync(path) == false) {

      fs.mkdirSync(path)

    }

    return path

  }

  saveImage(buffer: ArrayBuffer, type: string, name?: string): string | undefined {

    if (!name) {

      name = util.generateRandomUUID(false)

    }

    let path = this.getImageFileDir() + "/" + name

    return this.saveFile(buffer, type, path)

  }

  saveFile(buffer: ArrayBuffer | string, type: string, uri: string): string | undefined {

    let file: fs.File | undefined = undefined

    try {

      let path = uri + "." + type

      file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)

      fs.writeSync(file.fd, buffer)

      fs.closeSync(file)

      return path

    } catch (e) {

      try {

        if (file) {
          fs.close(file)
        }

        console.log("whiteImage error" + e)

      } catch (e) {

      }

      return undefined

    }

  }

  build() {

    Column() {

      Web({

        src: $rawfile('index.html'),

        controller: this.controller

      })

        .onShowFileSelector((event) => {

          console.log('MyFileUploader onShowFileSelector invoked')

          const photoSelectOptions = new picker.PhotoSelectOptions();

          photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;

          photoSelectOptions.maxSelectNumber = 5;

          let uris: Array<string> = [];

          const photoViewPicker = new picker.PhotoViewPicker();

          photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {

            uris = photoSelectResult.photoUris;

            // 图片压缩

            try {

              // Get URI

              let uri = uris[0];

              let type = uri.split(".").pop()

              let fd = fs.openSync(uri, fs.OpenMode.READ_ONLY).fd

              const imagePackerApi: image.ImagePacker = image.createImagePacker();

              const imageSourceApi: image.ImageSource = image.createImageSource(fd);

              let packOpts: image.PackingOption = { format: "image/jpeg", quality: 98 };

              imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => {

                if (err) {

                  console.error('packing failed.');

                } else {

                  let res = this.saveImage(data, type ?? "jpg")

                  // 获取选择的文件列表

                  event?.result.handleFileList([res]);

                }

              })

            } catch (error) {

              let err = error as BusinessError;

              hilog.error(0x0000, '', `the pick call failed. error code: ${err.code}`);

            }

          }).catch((err: BusinessError) => {

          })

          return true

        })

    }

  }
}

【index.html】

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Display Image URL</title>

<style>

#image-container {

margin-top: 10px;

}

#selected-image {

max-width: 100%;

height: auto;

}

</style>

</head>

<body>

<h1>Select an Image from System Gallery</h1>

<input type="file" id="file-input" accept="image/*">

<div id="image-container">

<p id="image-url"></p>

<img id="selected-image" alt="Selected Image">

</div>

<script>

document.getElementById('file-input').addEventListener('change', function(event) {

var file = event.target.files[0];

if (file) {

var imageUrl = URL.createObjectURL(file);

document.getElementById('image-url').textContent = imageUrl;

document.getElementById('selected-image').src = imageUrl;

} else {

document.getElementById('image-url').textContent = '';

document.getElementById('selected-image').src = '';

  }

});

</script>

</body>

</html>

更多关于HarmonyOS 鸿蒙Next Uri 问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对HarmonyOS鸿蒙Next中的Uri问题,以下是一些可能的解决方案:

  1. 检查Uri格式:确保Uri格式正确,符合HarmonyOS的规范。Uri中的字符应正确编码,避免非法字符导致的问题。
  2. 验证Uri有效性:确认Uri是否有效且对应的资源或页面存在。无效的Uri或不存在的资源会导致跳转或加载失败。
  3. 检查页面配置:对于Uri指向的页面,确保已在main_pages.json中正确配置。检查路径是否与配置一致,特别注意路径中的斜杠(/)是否多余或缺失。
  4. 跨模块跳转:如果是跨模块跳转,确保使用了正确的跳转方法,如pushNamedRoute,并检查目标模块是否已正确部署和配置。
  5. 清除缓存:清除项目缓存,重新编译并运行项目,以确保所有配置更改已生效。

如果以上方法均无法解决问题,可能是由于更复杂的系统或应用问题导致。此时,建议联系HarmonyOS的官方客服以获取更专业的帮助。官网地址是:https://www.itying.com/category-93-b0.html

回到顶部