HarmonyOS鸿蒙Next中webview嵌入的html片段内的img标签如何展示沙箱内的图片
HarmonyOS鸿蒙Next中webview嵌入的html片段内的img标签如何展示沙箱内的图片
webview嵌入的html片段内的img标签如何展示沙箱内的图片
同样的问题,楼主解决没?是不是只能转base64了?
更多关于HarmonyOS鸿蒙Next中webview嵌入的html片段内的img标签如何展示沙箱内的图片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
使用Image组件, 得到文件沙箱路径后, 调用@ohos.file.fileuri模块的fileuri.getUriFromPath(file.path)将沙箱路径转化为沙箱uri, 传入之后即可正常显示.
示例:
import fileUri from '[@ohos](/user/ohos).file.fileuri';
import common from '[@ohos](/user/ohos).app.ability.common';
import fs from '[@ohos](/user/ohos).file.fs';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State uri: string = ""
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
let context = getContext(this) as common.UIAbilityContext
let filePath = context.filesDir + "/test.png"
let arrayBuff = context.resourceManager.getRawFileContentSync("icon.png").buffer
console.log('testTag-----',arrayBuff)
let file = fs.openSync(filePath,fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
fs.writeSync(file.fd,arrayBuff)
this.uri = fileUri.getUriFromPath(filePath)
console.log('testTag-----',filePath)
})
Image(this.uri)
.width(100)
.height(100)
}
}
.width('100%')
}
.height('100%')
}
参考文档 用Image组件如何显示沙箱路径的图片,
沙箱路径例如 /data/storage/el2/base/haps/entry/files/IMG_1701270974000.jpg
应用沙箱目录-应用文件-Core File Kit(文件基础服务)-应用框架 - 华为HarmonyOS开发者
在HarmonyOS鸿蒙Next中,如果需要在WebView中嵌入的HTML片段内的<img>标签展示沙箱内的图片,可以通过以下步骤实现:
-
获取沙箱内图片路径:首先,确保图片文件存储在应用的沙箱目录中,例如
internal://cache或internal://files。 -
将沙箱路径转换为WebView可访问的URI:使用
Context的getFilesDir()或getCacheDir()方法获取沙箱目录路径,然后通过FileProvider或其他方式将其转换为WebView可识别的URI。 -
在HTML中嵌入图片:将转换后的URI作为
<img>标签的src属性值嵌入到HTML片段中。
示例代码:
String imagePath = context.getFilesDir() + "/image.png";
String imageUri = "file://" + imagePath;
String html = "<html><body><img src='" + imageUri + "'/></body></html>";
webView.loadData(html, "text/html", "UTF-8");
- 处理权限和安全性:确保WebView的配置允许加载本地文件,并处理可能的安全性问题。
通过以上步骤,可以在鸿蒙Next的WebView中展示沙箱内的图片。
在HarmonyOS鸿蒙Next中,若要在WebView中嵌入的HTML片段内展示沙箱内的图片,可以通过以下步骤实现:
-
将图片放入沙箱目录:确保图片文件已放置在应用的沙箱目录中,例如
internal://cache/或internal://files/。 -
生成文件URL:使用
Context.getFilesDir()或Context.getCacheDir()获取沙箱目录路径,并生成文件URL。 -
在HTML中引用图片:将生成的URL嵌入到HTML片段的
<img>标签的src属性中,例如:<img src="internal://cache/your_image.png" alt="Image"> -
加载HTML到WebView:使用
WebView.loadData()或WebView.loadDataWithBaseURL()方法加载HTML片段。
注意:确保WebView的setAllowFileAccess(true)已启用,以允许访问本地文件。

