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

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

阅读 504
1 个回答

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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏