问题
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.
- 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;
}
}
- 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