Maui 读取外部文件显示到Blazor中 - dotnet-simple
source link: https://www.cnblogs.com/hejiale010426/p/17040997.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Maui 读取外部文件显示到Blazor中
首先在maui blazor中无法直接读取外部文件显示 ,但是可以通过base64去显示 但是由于base64太长可能影响界面卡顿
这个时候我们可以使用blob链接去加载外部图片 它不需要copy文件到wwwroot中 它会将byte转换一个url供blaozr去读取
来看实现 :
首先第一步在wwwroot中的index.html添加一个js方法 用来将byte转换blob链接 将以下方法复制进去
<script>
/**
* 将图片字节数组转换blob url
*/
function imgToLink(blob) {
var myBlob = new Blob([blob], { type: "image/png" });
return (window.URL || window.webkitURL || window || {}).createObjectURL(myBlob);
}
</script>
如何我们在Index.razor中添加以下代码
@page "/"
@inject IJSRuntime JS
<img src="@url" height="200px" width="200"/>
@code
{
private string url;
protected override async Task OnInitializedAsync()
{
// 放在项目目录下的logo.png会被打包到cache文件夹中 这里你也可以放外部文件链接 但是你需要保证再读取前有读取权限负责会报错
var logo = Path.Combine(FileSystem.CacheDirectory, "logo.png");
// 读取转换byte[]
var data = await File.ReadAllBytesAsync(logo);
// 通过js转换blob链接
url = await JS.InvokeAsync<string>("imgToLink", data);
await base.OnInitializedAsync();
}
}
完成以后我们将图片添加到项目中!
修改图片属性为始终复制:
然后我们将程序直接执行
这种效果比转base64更好不会再界面残留太多字符串 推荐使用,如果你有更好的办法请推荐给我
来着token的分享
技术交流群:737776595
本文作者:dotnet-simple
本文链接:https://www.cnblogs.com/hejiale010426/p/17040997.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK