如何在 Blazor 应用中下载文件
此处下载指的是 Blazor 全栈项目内,客户端网页如何向后端请求文件并下载。
1. 注入 JS 互操作
1
| @inject IJSRuntime jsRuntime
|
2. 在 html 部分添加脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <div class="mx-auto status-panel "> @foreach (var file in downloadedFiles) { <div class="apk-file" @onclick="() => TransmitCachedApk(file)">@file</div> } </div>
<script> window.downloadFileFromStream = async (fileName, contentStreamReference) => { console.log("Downloading file: " + fileName); const arrayBuffer = await contentStreamReference.arrayBuffer(); const blob = new Blob([arrayBuffer]); const url = URL.createObjectURL(blob); const anchorElement = document.createElement('a'); anchorElement.href = url; anchorElement.download = fileName ?? ''; anchorElement.click(); anchorElement.remove(); URL.revokeObjectURL(url); } </script>
|
3. 使用 JS 互操作
注意:当直接返回一个物理文件的 stream 时,需要使用 File.OpenRead
,并用 DotNetStreamReference
处理一次。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @code { private List<string> downloadedFiles = new List<string>(); private async Task TransmitCachedApk(string filename) { await DownloadApk(filename); }
private async Task DownloadApk(string apk) { Log.Information("Transmitting cached apk {apk}", apk); var fileStream = File.OpenRead($"apk/{apk}"); using var streamRef = new DotNetStreamReference(stream: fileStream); await jsRuntime.InvokeVoidAsync("downloadFileFromStream", apk, streamRef); } }
|
见微软文档 ASP.NET Core Blazor 文件下载 | Microsoft Learn
对于必须返回物理文件的 Stream 的服务器侧应用中的组件,组件可以调用 File.OpenRead
1 2 3 4 5 6 7 8 9 10 11
| private Stream GetFileStream() => File.OpenRead(@"{PATH}");
private async Task DownloadFileFromStream() { var fileStream = GetFileStream(); var fileName = "log.bin";
using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef); }
|