Blazor下载文件

法一:

@using System.IO
@inject IJSRuntime JS

<PageTitle>File Download 1</PageTitle>

<h1>File Download Example 1</h1>

<button @onclick="DownloadFileFromStream">
Download File From Stream
</button>

@code {
private Stream GetFileStream()
{
var randomBinaryData = new byte[50 * 1024];
var fileStream = new MemoryStream(randomBinaryData);

return fileStream;
}

private async Task DownloadFileFromStream()
{
var fileStream = GetFileStream();
var fileName = "log.bin";

using var streamRef = new DotNetStreamReference(stream: fileStream);

await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}
}

 

法二

@inject IJSRuntime JS

<PageTitle>File Download 2</PageTitle>

<h1>File Download Example 2</h1>

<button @onclick="DownloadFileFromURL">
Download File From URL
</button>

@code {
private async Task DownloadFileFromURL()
{
var fileName = "quote.txt";
var fileURL = "/files/quote.txt";
await JS.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);
}
}

posted @ 2024-03-03 10:32  Biyuanguang  阅读(31)  评论(0编辑  收藏  举报