天天看点

Blazor server-side 下载文件添加 WebApi Controller添加 JS 下载功能函数在组件中使用 JS 函数下载文件参考

目录

  • 添加 WebApi Controller
    • 1、添加控制器代码
    • 2、修改 Startup.cs
  • 添加 JS 下载功能函数
    • 1、修改 _Host.cshtml 文件
  • 在组件中使用 JS 函数下载文件
  • 参考

添加 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/