如何在 Maui Blazor 使用 BlazorWebView 像本机浏览器一样下载文件?
总结: Windows 和 Android 可以实现, ios/mac 使用的是 WKWebView , 研究了一部分,感兴趣的大佬接棒吧.
关键代码
MainPage.xaml.cs
#if ANDROID
using Android.Webkit;
using AndroidX.Activity;
#elif WINDOWS
using Microsoft.Web.WebView2.Core;
#endif
protected string UploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "uploads");
public MainPage()
{
InitializeComponent();
blazorWebView.BlazorWebViewInitialized += BlazorWebViewInitialized;
}
private void BlazorWebViewInitialized(object? sender, BlazorWebViewInitializedEventArgs e)
{
#if ANDROID
if (e.WebView.Context?.GetActivity() is not ComponentActivity activity)
{
e.WebView.Download +=(async (s,e)=> await WebView_DownloadAsync(s,e));
}
#elif WINDOWS
e.WebView.CoreWebView2.DownloadStarting += (async (s, e) => await CoreWebView2_DownloadStartingAsync(s, e));
#endif
}
#if WINDOWS
private async Task CoreWebView2_DownloadStartingAsync(object sender, CoreWebView2DownloadStartingEventArgs e)
{
var downloadOperation = e.DownloadOperation;
string fileName = Path.GetFileName(e.ResultFilePath);
var filePath = Path.Combine(UploadPath, fileName);
e.ResultFilePath = filePath;
await DisplayAlert("提示", $"下载文件完成 {fileName}", "OK");
}
#endif
#if ANDROID
private async Task WebView_DownloadAsync(object sender, DownloadEventArgs e)
{
Uri uri = new Uri(e.Url);
string fileName = Path.GetFileName(uri.LocalPath);
var httpClient = new HttpClient();
var filePath = Path.Combine(UploadPath, fileName);
byte[] fileBytes = await httpClient.GetByteArrayAsync(e.Url);
File.WriteAllBytes(filePath, fileBytes);
await DisplayAlert("提示", $"下载文件完成 {fileName}", "OK");
}
#endif
ios/mac的思路,拦截这里
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
blazorWebView.BlazorWebViewInitialized += BlazorWebViewInitialized;
blazorWebView.BlazorWebViewInitializing += BlazorWebViewInitializing;
blazorWebView.UrlLoading +=
(sender, urlLoadingEventArgs) =>
{
if (urlLoadingEventArgs.Url.Host != "0.0.0.0")
{
//外部链接WebView内打开,例如pdf浏览器
Console.WriteLine(urlLoadingEventArgs.Url);
urlLoadingEventArgs.UrlLoadingStrategy =
UrlLoadingStrategy.OpenInWebView;
//拦截可处理 IOS || MACCATALYST 下载文件, 简单测试一下
if (urlLoadingEventArgs.Url.ToString().EndsWith(".exe"))
{
Task.Run(async () => await DownloadAsync(urlLoadingEventArgs.Url.ToString()));
}
}
};
}
大神可以研究一下ios文章: https://dev.to/gualtierofr/download-files-in-a-wkwebview-boo
截图很大,将就一下吧
截图
Android
WSA
Windows
WinUI3
Winforms
WPF
关联项目
FreeSql QQ群:4336577
BA & Blazor QQ群:795206915
Maui Blazor 中文社区 QQ群:645660665
知识共享许可协议
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名AlexChow(包含链接: https://github.com/densen2014 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系 。
转载声明
本文来自博客园,作者:周创琳 AlexChow,转载请注明原文链接:https://www.cnblogs.com/densen2014/p/17202103.html
AlexChow
今日头条 | 博客园 | 知乎 | Gitee | GitHub