【发布时间】:2021-09-25 11:45:15
【问题描述】:
在 blazor 中将文件从服务器下载到客户端时,似乎还没有最佳实践(如果我错了,请纠正我)。一个好的解决方案似乎是实现一个返回文件流的控制器(就像在这里完成的:How to download in-memory file from Blazor server-side),还有更多涉及 javascript 的面向客户端的解决方案(例如:How can one generate and save a file client side using Blazor?)。然而,这些似乎都不完全适合我的问题。
我想要的是一种解决方案,它可以让我开始从服务器到客户端的大文件并行下载流。目前我正在使用一个控制器,它从内存中的给定目录中获取和压缩文件。我希望用户能够从同一页面客户端启动多个下载流。这目前不适用于我的控制器,因为它会重定向用户并且用户必须等到下载完成才能开始下一个。在 blazor 中提供并行下载的好方法是什么?
这是我目前拥有的(简化的):
控制器:
[ApiController]
[Route("[controller]")]
public class DownloadController : Controller
{
[HttpGet("{directory}/{zipFileName}")]
[DisableRequestSizeLimit]
public IActionResult DownloadZipFile(string directory, string zipFileName)
{
directory = System.Net.WebUtility.UrlDecode(directory);
if (Directory.Exists(directory))
{
using (ZipFile zip = new ZipFile())
{
var files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
foreach (var f in files)
{
zip.AddFile(f,Path.GetDirectoryName(f).Replace(directory, string.Empty));
}
using (MemoryStream memoryStream = new MemoryStream())
{
zip.Save(memoryStream);
return File(memoryStream.ToArray(), "application/zip", String.Format(zipFileName));
}
}
}
else
{
// error handling
}
}
}
剃刀页面:
<button @onclick="()=>DownloadZip(zipFilePath)">download file</button>
@code {
protected string zipFilePath= @"C:\path\to\files";
protected void DownloadZip(string zipFilePath)
{
NavigationManager.NavigateTo("api/download/" + System.Net.WebUtility.UrlEncode(zipFilePath) + "/ZipFileName.zip", true);
}
}
【问题讨论】:
标签: c# download controller blazor blazor-server-side