Is there a way to download a file, generated dynamically in memory in Blazor Server Side without need to store it on a filesystem?
The solution was in adding Web Api contoller into Blazor server side app.
Controllers/DownloadController.cs
controller to the root of Blazor app:[ApiController, Route("api/[controller]")]
public class DownloadController : ControllerBase {
[HttpGet, Route("{name}")]
public ActionResult Get(string name) {
var buffer = Encoding.UTF8.GetBytes("Hello! Content is here.");
var stream = new MemoryStream(buffer);
//var stream = new FileStream(filename);
var result = new FileStreamResult(stream, "text/plain");
result.FileDownloadName = "test.txt";
return result;
}
}
Startup.cs
of the Blazor app to support controllers routing:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
...
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action}");
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
Create a cshtml page in Blazor like bellow.
FileDownload.cshtml.cs:
public class FileDownloadsModel : PageModel
{
public async Task<IActionResult> OnGet()
{
byte[] fileContent = ....;
return File(fileContent, "application/force-download", "test.txt");
}
}
FileDownload.cshtml:
@page "/download/{object}/{id:int}/{fileType}"
@model GFProdMan.Pages.FileDownloadsModel
And that is simply it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With