HarmonyOS Uri问题?

Web 中通过onShowFileSelector 调用原生图片选择器。选择图片后回传给 H5。

使用 PhotoViewPicker 选择图片后,不做任何处理,回调给 H5,其能正常收到数据并展示,因为选择后返回的数据是一个 uri。

问题:

如果进行图片压缩,并将压缩后的图片的path转换为 uri(通过 fileuri.getUriFromPath 方法),则 H5 无法收到数据并展示。压缩后的图片是真实存在的

那我要怎么编写这个 uri 呢

阅读 454
1 个回答

请参考以下示例修改:

【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>
logo
HarmonyOS
子站问答
访问
宣传栏