Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download in-memory file from Blazor server-side

Is there a way to download a file, generated dynamically in memory in Blazor Server Side without need to store it on a filesystem?

like image 527
Yurii Zhukow Avatar asked Jan 05 '20 01:01

Yurii Zhukow


2 Answers

The solution was in adding Web Api contoller into Blazor server side app.

  1. Add 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;
        }


    }
  1. Adjust 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");

            });

        }
like image 123
Yurii Zhukow Avatar answered Sep 18 '22 05:09

Yurii Zhukow


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.

like image 43
MarchalPT Avatar answered Sep 21 '22 05:09

MarchalPT