HarmonyOS Uri问题

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

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

问题:

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

那我要怎么编写这个 uri 呢

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

请参考以下示例修改:

【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>
分享
微博
QQ
微信
回复
3天前
相关问题
HarmonyOS uri编码解码问题
64浏览 • 1回复 待解决
HarmonyOS 拍照返回uri转bitmap问题
569浏览 • 1回复 待解决
HarmonyOS Want使用uri Schema唤醒app的问题
446浏览 • 1回复 待解决
HarmonyOS 推送和uri配置
397浏览 • 1回复 待解决
HarmonyOS uri获取query失败
52浏览 • 2回复 待解决
HarmonyOS uri如何替换schema
66浏览 • 1回复 待解决
HarmonyOS uri.port返回异常
18浏览 • 1回复 待解决
HarmonyOS /data/local/tmp路径uri获取
36浏览 • 1回复 待解决
如何根据uri读取文件?
3178浏览 • 1回复 待解决
HarmonyOS rawfile中的文件如何获取URI
49浏览 • 1回复 待解决
使用FilePick上传uri失败,报错201
1803浏览 • 1回复 待解决
#鸿蒙通关秘籍#如何从URI获取路径?
102浏览 • 1回复 待解决
hdc shell命令是否支持schema uri模拟跳转
1967浏览 • 1回复 待解决