MAUI Blazor混合项目:Excel下载后打开及多设备下载路径获取
在MAUI Blazor中打开下载的Excel文件并获取跨平台下载路径
获取各设备的下载文件夹路径
MAUI 自带的 FileSystem 静态类可以直接获取跨平台的标准下载目录,无需手动处理不同设备的用户名差异,它会自动映射到对应系统的下载路径:
- Windows:
C:\Users\<用户名>\Downloads - macOS:
/Users/<用户名>/Downloads - Android:
/storage/emulated/0/Download - iOS:应用沙盒内的 Downloads 目录(需配置权限)
代码示例
using Microsoft.Maui.Storage; // 获取下载路径 private string GetDownloadDirectory() { return FileSystem.DownloadsDirectory; }
权限配置
- Android:在
AndroidManifest.xml中添加必要权限(Android 13+ 需适配新权限):<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" /> <uses-permission android:name="android.permission.READ_MEDIA_DOCUMENTS" /> - iOS:在
Info.plist中添加访问说明:<key>NSDocumentFolderUsageDescription</key> <string>需要访问下载目录以打开Excel文件</string>
打开已下载的Excel文件
使用 MAUI 的 Launcher 类可以调用系统默认应用打开指定文件,步骤如下:
代码示例
using Microsoft.Maui.ApplicationModel; using Microsoft.Maui.Storage; using System.IO; private async Task OpenDownloadedExcelFile() { string downloadPath = FileSystem.DownloadsDirectory; string excelFilePath = Path.Combine(downloadPath, "excelfile.xls"); if (File.Exists(excelFilePath)) { // 根据文件类型设置MIME类型:.xls用application/vnd.ms-excel,.xlsx用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet var openRequest = new OpenFileRequest { File = new ReadOnlyFile(excelFilePath), ContentType = "application/vnd.ms-excel" }; await Launcher.OpenAsync(openRequest); } else { // 文件不存在时提示用户 await JS.InvokeVoidAsync("alert", "Excel文件未找到,请先完成下载"); } }
注意事项:JS下载的文件路径问题
如果你的 TableToExcel 方法是通过JS在WebView中触发浏览器式下载,文件可能会存到WebView的默认下载目录而非MAUI的标准下载目录。此时需要拦截WebView的下载事件,将文件保存到指定路径:
- 在
MainPage.xaml中给BlazorWebView绑定下载事件:
<BlazorWebView HostPage="wwwroot/index.html" DownloadStarting="BlazorWebView_DownloadStarting"> <BlazorWebView.RootComponents> <RootComponent Selector="#app" ComponentType="{x:Type local:Main}" /> </BlazorWebView.RootComponents> </BlazorWebView>
- 在
MainPage.xaml.cs中实现事件处理:
private async void BlazorWebView_DownloadStarting(object sender, DownloadStartingEventArgs e) { e.Cancel = true; // 取消WebView默认下载行为 string savePath = Path.Combine(FileSystem.DownloadsDirectory, e.SuggestedFileName); // 下载文件到指定路径 using var httpClient = new HttpClient(); using var stream = await httpClient.GetStreamAsync(e.Url); using var fileStream = new FileStream(savePath, FileMode.Create); await stream.CopyToAsync(fileStream); // 下载完成后直接打开文件 await OpenDownloadedExcelFile(); }
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

