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

独自空忆成欢 提交于 2021-01-21 08:35:13

问题


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


回答1:


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");

            });

        }


来源:https://stackoverflow.com/questions/59596338/how-to-download-in-memory-file-from-blazor-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!