HarmonyOS H5调用APP图库选择图片

通过PhotoViewPicker打开图库选择图片后得到的是file://xxxx.jpg,如何转换成前端H5浏览器识别的File文件

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

可以参考下面的方式:可以读取路径,拿到图片数据后base64编码,使用runJavascript传给前端。以下是demo:

index.ets

import web_webview from '@ohos.web.webview'
import { common } from '@kit.AbilityKit'
import { uri, util } from '@kit.ArkTS'
import fs from '@ohos.file.fs';
import picker from '@ohos.file.picker'
import { BusinessError } from '@kit.BasicServicesKit';

class testClass {
  base64Str: string

  constructor(base64Str:string) {
    this.base64Str=base64Str;
  }

  test(): string {
    return "2123";
  }

  toString(): void {
    console.log('Web Component toString');
  }
}

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  //定义一个全局的string类型的数组,用来存放通过picker拉起后选择完图片后图片的uri
  @State uris: Array<string> = []
  @State base64Str : string = ""
  @State testObj: testClass = new testClass(this.base64Str);
  aboutToAppear() {
    web_webview.WebviewController.setWebDebuggingAccess(true);
  }
  build() {
    Column() {

      Web({ src: $rawfile('TestonShowFileSelector.html'), controller: this.controller })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .onShowFileSelector((event) => {
          // //-------调用相册-------------------------
          console.log('MyFileUploader onShowFileSelector invoked')
          const photoSelectOptions = new picker.PhotoSelectOptions();
          // 过滤选择媒体文件类型为IMAGE_VIDEO_TYPE
          photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
          // 选择媒体文件的最大数目
          photoSelectOptions.maxSelectNumber = 8;
          //let uris: Array<string> = [];
          const photoViewPicker = new picker.PhotoViewPicker();
          photoViewPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
            this.uris = photoSelectResult.photoUris;
            let file1 = fs.openSync(this.uris[0])
            let array:ArrayBuffer = new ArrayBuffer(fs.statSync(file1.fd).size)
            fs.readSync(file1.fd,array)
            let unit = new Uint8Array(array)
            let base64 = new util.Base64Helper();
            let mystr = base64.encodeToStringSync(unit);
            this.base64Str = "myFunction( \ "" + mystr + " \ ")"
            this.controller.runJavaScript(this.base64Str)
            console.info('photoViewPicker.select to file succeed and uris are:' + this.uris);//file://media/Photo/11/IMG_1713942933_005/IMG_20240424_151353.jpg
          }).catch((err: BusinessError) => {
            console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
          })

          return false
        })

    }
  }
}

TestonShowFileSelector.html

<!DOCTYPE html>
  <html>
  <head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8">
  <script>
  function myFunction(mystr)
  {
    var img = new Image();
    img.width = 100;
    img.height = 50;
    img.src = "data:image/png;base64,"+mystr;
    document.body.appendChild(img);
    <!-- let str=objName.test()-->
  console.log(mystr)
    console.log("这部分是将ArkTS发送过来的str渲染到h5页面上,或者存在h5侧的变量中")
  }
window.onload = function() {
  // 获取文件输入元素
  var fileInput = document.getElementById('upload');

  // 监听文件输入的改变事件
  fileInput.addEventListener('change', function(e) {
    // 获取选中的文件
    var file = e.target.files[0];
    // 创建一个FileReader对象
    var reader = new FileReader();

    // 定义文件读取完成后的回调函数
    reader.onloadend = function() {
      // 获取图片元素
      var img = document.getElementById('preview');
      // 将读取到的结果赋值给图片元素的src属性
      img.src = reader.result;
    }

    // 读取文件内容
    if (file) {
      reader.readAsDataURL(file);
    }
  });
}


  </script>
  </head>
  <body>
  <form id="upload-form" enctype="multipart/form-data">
  <!-- 修改type属性为camera -->
  <input type="file" id="upload" name="upload" accept="image/*" capture="camera" />
  <!-- 添加一个图片元素用于展示图片 -->
  <img id="preview"/>
  </form>
  <div id="155134"></div>
  </body>
  </html>
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS H5调用原生扫码功能
82浏览 • 1回复 待解决
HarmonyOS h5拉起app,如何获取参数
29浏览 • 1回复 待解决
HarmonyOS h5想要唤起app如何处理
44浏览 • 1回复 待解决
HarmonyOS h5 web上传图片,文件的demo
28浏览 • 1回复 待解决
HarmonyOS h5客服无法上传相册的图片
28浏览 • 1回复 待解决
HarmonyOS 浏览器访问H5,并唤起App
25浏览 • 1回复 待解决
HarmonyOSh5前端侧调用应用侧方法
58浏览 • 2回复 待解决
HarmonyOS web组件加载h5h5拉起摄像头
615浏览 • 1回复 待解决
HarmonyOS 本地H5加载
61浏览 • 1回复 待解决
app内嵌入H5网页登录储存
469浏览 • 1回复 待解决
HarmonyOS H5页面保存图片到本地相册
37浏览 • 1回复 待解决