HarmonyOS鸿蒙Next中webview如何加载本地路径的图片和视频

HarmonyOS鸿蒙Next中webview如何加载本地路径的图片和视频 请教 webview 如何加载本地路径的图片和视频;可以直接加载相册里面的图片和视频吗?

4 回复

可以用loadData 加载指定的数据

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-webview-V5#loaddata

// xxx.ets
import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';

@Entry
@Component
struct WebComponent {

  controller: web_webview.WebviewController = new web_webview.WebviewController();
  updataContent: string = '<body><div><image src=resource://rawfile/xxx.png alt="image -- end" width="500" height="250"></div></body>'

  build() {
    Column() {
      Button('loadData')
        .onClick(() => {
          try {
            this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " ");
          } catch (error) {
            let e: business_error.BusinessError = error as business_error.BusinessError;
            console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);
          }
        })
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}

更多关于HarmonyOS鸿蒙Next中webview如何加载本地路径的图片和视频的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


不可以,需要先保存到沙盒路径中

在HarmonyOS鸿蒙Next中,WebView加载本地路径的图片和视频可以通过使用file://协议来实现。具体步骤如下:

  1. 图片加载

    • 将图片文件放置在应用的resources目录下,例如resources/base/media/image.png
    • 在WebView中使用file://协议加载图片:
      <img src="file:///resources/base/media/image.png" alt="Local Image">
      
  2. 视频加载

    • 将视频文件放置在应用的resources目录下,例如resources/base/media/video.mp4
    • 在WebView中使用file://协议加载视频:
      <video controls>
          <source src="file:///resources/base/media/video.mp4" type="video/mp4">
      </video>
      
  3. 注意事项

    • 确保文件路径正确,且文件存在于指定位置。
    • 文件的权限设置需要允许应用访问。

在HarmonyOS鸿蒙Next中,WebView加载本地路径的图片和视频可以通过以下步骤实现:

  1. 将资源文件放入应用目录:将图片和视频文件放入应用的资源目录(如resources/base/media)。

  2. 构建本地文件路径:使用context.getCacheDir()context.getFilesDir()获取文件路径,并拼接到资源文件。

  3. 使用file://协议加载:在WebView中使用file://协议加载本地文件路径。示例代码如下:

WebView webView = findComponentById(ResourceTable.Id_webview);
String localFilePath = "file://" + getContext().getCacheDir() + "/your_image_or_video_file";
webView.load(localFilePath);

确保文件路径正确,并处理权限和异常情况。

回到顶部