HarmonyOS webView怎么加载应用沙箱内的图片

应用内嵌入的h5页面,怎么加载沙箱中的文件

HarmonyOS
2024-12-23 15:14:33
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

H5页面无法通过以"file:…"形式加载沙箱内图片,可以将图片转成base64字符串,传递给H5页面,参考代码如下:

import { common } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';
import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct Page4 {
  webController: webview.WebviewController = new webview.WebviewController();
  @State test: Test = new Test()
  build() {
    Column(){
      Web({src:$rawfile('index2.html'),controller:this.webController})
        .javaScriptProxy({
          object: this.test,
          name: "picture",
          methodList: ["chosePicture"],
          controller: this.webController
        }).height("50%")
    }
  }
}

class Test{
  chosePicture() {
    let context = getContext(this) as common.UIAbilityContext
    let arrayBuff = context.resourceManager.getRawFileContentSync("startIcon.png")
    let base64helper = new util.Base64Helper()
    let base64string = base64helper.encodeToStringSync(arrayBuff,util.Type.MIME)
    console.debug(base64string)
    return base64string
  }
}


<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>

  <button id="init" onclick="takePicture()">获取沙箱路径图片</button>
  <img src="" id="myImage" alt="">
  </body>
  </html>

  <script>
  function takePicture() {
    let s = 'data:image/png;base64,' + picture.chosePicture();
    console.log(s)
    document.getElementById('myImage').src =  s;
  }
  </script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
分享
微博
QQ
微信
回复
2024-12-23 19:12:20
相关问题
Image组件如何读入沙箱内图片
3977浏览 • 1回复 待解决
HarmonyOS应用沙箱内创建目录失败
822浏览 • 1回复 待解决
HarmonyOS webview如何加载沙箱html
1351浏览 • 1回复 待解决
HarmonyOS WebView 延迟加载图片
788浏览 • 1回复 待解决
如何使用Image加载沙箱路径图片资源
2628浏览 • 2回复 待解决
应用沙箱图片保存到图库
2300浏览 • 1回复 待解决
图片同步加载怎么操作?
861浏览 • 1回复 待解决
HarmonyOS webview如何播放本地沙箱视频
2868浏览 • 1回复 待解决
HarmonyOS web加载沙箱文件失败
827浏览 • 1回复 待解决
HarmonyOS web从本地沙箱加载
932浏览 • 1回复 待解决
HarmonyOS 应用中如何加载磁盘图片
964浏览 • 1回复 待解决