有没有办法让文件流下载到Blazor中的浏览器? [英] Is there a way to get a file stream to download to the browser in Blazor?

查看:590
本文介绍了有没有办法让文件流下载到Blazor中的浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与Blazor一起尝试一些事情,但我仍然是新手.我正在尝试获取文件流以下载到浏览器.从Blazor将文件下载到浏览器的最佳方法是什么?

I'm trying out a few things with Blazor and I'm still new to it. I'm trying to get a file stream to download to the browser. What's the best way to download a file from Blazor to browser?

我尝试在剃刀视图中使用一种方法,该方法返回流,但不起作用.

I've tried using a method in my razor view that returns a stream but that didn't work.

//In my Blazor view
@code{
    private FileStream Download()
    {
        //get path + file name
        var file = @"c:\path\to\my\file\test.txt";
        var stream = new FileStream(test, FileMode.OpenOrCreate);
        return stream;
    }
}

上面的代码没有给我任何东西,甚至没有错误

The code above doesn't give me anything, not even an error

推荐答案

另一种解决方案是使用endpoints.MapControllerRoute添加一个简单的api控制器终结点.不过,这仅适用于服务器端服务器.

Another solution is to add a simple api controller endpoint using endpoints.MapControllerRoute. This will work only with server side blazor though.

例如:

endpoints.MapBlazorHub();
endpoints.MapControllerRoute("mvc", "{controller}/{action}");
endpoints.MapFallbackToPage("/_Host");

然后添加一个控制器.例如:

Then add a controller. For example:

public class InvoiceController : Controller
{
    [HttpGet("~/invoice/{sessionId}")]
    public async Task<IActionResult> Invoice(string sessionId, CancellationToken cancel)
    {
        return File(...);
    }
}

.razor文件中的用法:

Usage in a .razor file:

async Task GetInvoice()
{
    ...
    Navigation.NavigateTo($"/invoice/{orderSessionId}", true);
}

这篇关于有没有办法让文件流下载到Blazor中的浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆