Blazor server-side 下载文件

本文介绍了如何在Blazor应用中通过WebApiController提供文件下载功能,包括添加控制器代码、配置Startup.cs以启用API支持,以及在_Host.cshtml中使用JS下载文件的方法。详细步骤参考了相关技术资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加 WebApi Controller

对于服务侧 Blazor 采用通过 WebApi 的方式下载文件。

1、添加控制器代码

[ApiController, Route("api/[controller]/[action]")]
public class DownloadController : ControllerBase 
{
	[HttpGet]
	public async Task<ActionResult> Get(string name) 
	{
		string filePath = System.IO.Path.Combine(AppDomain.CurrentDoMain.BaseDirectory, name);
		if (!System.IO.File.Exists(filePath))
		{
			return NotFound();
		}
		byte[] buffer = await System.IO.File.ReadAllBytesAsync(filePath);
		rethrn File(buffer, "application/octet-stream", "文件名");
    }
}

2、修改 Startup.cs

增加 WebApi Controller 支持

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
{
	...
	
	app.UseRouting();

	app.UseEndpoints(endpoints => 
	{
	 	endpoints.MapControllerRoute(
	 	name: "default",
	 	pattern: "{controller}/{action}");

		...

	});
}

添加 JS 下载功能函数

1、修改 _Host.cshtml 文件

将以下代码添加进 _Host.cshtml

<script>
	function saveAsFile(downloadLink, filename) {
		var link = document.createElement('a');
		link.download = filename;
		link.href = downloadLink;
		document.body.appendChild(link); // Needed for Firefox
		link.click();
		document.body.removeChild(link);
	}
 </script>

在组件中使用 JS 函数下载文件

@inject IJSRuntime JSRuntime

<button class="btn btn-primary" 
		@onclick="Download">DownloadFile
</button>

@code {
	private async Task Download()
	{
		string fileName = "file.txt";
		await JSRunTime.InvokeVoidSync(
			"saveAsFile", 
			$"http://localhost:5000/Download/Get?name={fileName}",
			"file.txt");
	}
}

参考

https://stackoverflow.com/a/59607207
https://www.grapecity.com/componentone/docs/blazor/online-blazor/exporting_data.html
https://wellsb.com/csharp/aspnet/blazor-jsinterop-save-file/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值