学习020-02-03 How to: Download a File in XAF Blazor Applications(如何在XAF Blazor应用程序中下载文件)

How to: Download a File in XAF Blazor Applications(如何在XAF Blazor应用程序中下载文件)

This topic describes different ways to enable file download functionality in XAF ASP.NET Core Blazor applications. Examples in this topic use the tutorial application for demonstration purposes, but you can easily adapt these steps to suit your needs.
本主题介绍了在 XAF ASP.NET Core Blazor 应用程序中启用文件下载功能的不同方法。本主题中的示例使用教程应用程序进行演示,但您可以轻松调整这些步骤以满足您的需求。

For information on how to upload files in XAF Blazor, refer to the following topic: How to: Use a Custom Action to Upload a File in a Popup Window.
有关如何在XAF Blazor中上传文件的信息,请参阅以下主题:如何:使用自定义操作在弹出窗口中上传文件。

Overview(概述)

XAF does not implement file download mechanisms and relies on ASP.NET Core API. The following sections contain examples that use this API in XAF Blazor applications:
XAF 未实现文件下载机制,而是依赖于 ASP.NET Core API。以下部分包含在 XAF Blazor 应用程序中使用此 API 的示例:

Microsoft documentation describes two mechanisms to download files:
微软文档描述了两种下载文件的机制:

1.Download a file from a stream (recommended for files smaller than 250 MB).
从流中下载文件(推荐用于小于250MB的文件)。

2.Download a file from a URL (recommended for files larger than 250 MB).
从URL下载文件(推荐用于大于250MB的文件)。

This topic demonstrates both of these approaches.
本主题展示了这两种方法。

Note
The sample below uses a void-returning async method for the Execute event handler. If you need to modify the suggested code, be aware that the caller of a void-returning async method cannot catch exceptions thrown by the method. Such unhandled exceptions may cause application failure. For more information about void-returning async methods, refer to the following Microsoft article: Async return types (C#) - Void return type.

以下示例对“执行”事件处理程序使用返回 void 的异步方法。如果需要修改建议的代码,请注意,调用返回 void 的异步方法的调用方无法捕获该方法引发的异常。此类未处理的异常可能会导致应用程序失败。有关返回 void 的异步方法的详细信息,请参阅以下 Microsoft 文章:异步返回类型(C#)- Void 返回类型。

Download a File From a Stream(从流中下载文件)

The example below uses JavaScript code to download a file. This code takes a link to a .NET stream (DotNetStreamReference) as a parameter. The application then calls this JavaScript code using the IJSRuntime service.
下面的示例使用JavaScript代码下载文件。此代码将指向 .NET 流(DotNetStreamReference)的链接作为参数。然后,应用程序使用IJSRuntime服务调用此JavaScript代码。

To integrate this file download method into your application, follow the steps below:
要将此文件下载方法集成到您的应用程序中,请按照以下步骤操作:

1.Add the following JavaScript code to the <body> tag of your Blazor project’s YourSolutionName.Blazor.Server/Pages/_Host.cshtml file:
将以下JavaScript代码添加到你的Blazor项目的YourSolutionName.Blazor.Server/Pages/_Host.cshtml文件的<body>标签中:

HTML
<html>
    <body>
        @if(isIE) {
            <!-- ... -->
        }
        else {
            <!-- ... -->
            <script>
            window.downloadFileFromStream = async (fileName, contentStreamReference) => {
                const arrayBuffer = await contentStreamReference.arrayBuffer();
                const blob = new Blob([arrayBuffer]);
                const url = URL.createObjectURL(blob);
                const anchorElement = document.createElement('a');
                anchorElement.href = url;
                anchorElement.download = encodeURIComponent(fileName) ?? '';
                anchorElement.click();
                anchorElement.remove();
                URL.revokeObjectURL(url);
            }
            </script>
        }
    </body>
</html>

2.Add a new file (DownloadFileController.cs) to your Blazor project. This file should contain a View Controller that allows files to be downloaded.
在你的Blazor项目中添加一个新文件(DownloadFileController.cs)。此文件应包含一个视图控制器,用于实现文件下载功能。

This controller adds a Download a File action to your application. When a user clicks the action, the application passes the fileContent value to the browser as a file.
此控制器为您的应用程序添加了“下载文件”操作。当用户点击该操作时,应用程序会将fileContent值作为文件传递给浏览器。

C#
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp;
using DevExpress.Persistent.Base;
using Microsoft.JSInterop;
using System.Text;


namespace YourSolutionName.Blazor.Server.Controllers;


public class DownloadFileController : ViewController {
    public DownloadFileController() {


        var downloadAction = new SimpleAction(this, "Download a File", PredefinedCategory.Save);


        downloadAction.Execute += async (s, e) => {


            IJSRuntime jsRuntime = Application.ServiceProvider.GetRequiredService<IJSRuntime>();
            var fileName = "Test.txt";


            // Replace this line with an actual stream, e.g. file stream File.OpenRead(filePath);
            var stream = new MemoryStream(Encoding.UTF8.GetBytes("YourData"));
            using var streamRef = new DotNetStreamReference(stream: stream);
            await jsRuntime.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
        };
    }
}

3.Run the application and click Download a File. The specified file is downloaded to the browser.
运行应用程序,然后点击“下载文件”。指定的文件将下载到浏览器中。

在这里插入图片描述

Download a File From a URL(从URL下载文件)

To integrate this file download method into your application, follow the steps below:
要将此文件下载方法集成到您的应用程序中,请按照以下步骤操作:

1.Add the following JavaScript code to the <body> tag of your Blazor project’s YourSolutionName.Blazor.Server/Pages/_Host.cshtml file:
将以下JavaScript代码添加到你的Blazor项目的YourSolutionName.Blazor.Server/Pages/_Host.cshtml文件的<body>标签中:

HTML    
<html>
    <body>
        @if(isIE) {
            <!-- ... -->
        }
        else {
            <!-- ... -->
            <script>
            window.triggerFileDownload = (fileName, url) => {
                const anchorElement = document.createElement('a');
                anchorElement.href = url;
                anchorElement.download = encodeURIComponent(fileName) ?? '';
                anchorElement.click();
                anchorElement.remove();
            }
            </script>
         }
    </body>
</html>

2.Create an endpoint (MVC controller) that provides access to the desired file. To do this, add a new file (FileController.cs) to the API folder of your Blazor project. Note that this controller should contain the Download method.
创建一个端点(MVC 控制器),以提供对所需文件的访问。为此,在 Blazor 项目的 API 文件夹中添加一个新文件(FileController.cs)。请注意,此控制器应包含 Download 方法。

By default, ASP.NET Core Blazor Application projects do not include the API folder. You may need to create it.
默认情况下,ASP.NET Core Blazor 应用程序项目不包含“API”文件夹。你可能需要创建该文件夹。

File: YourSolutionName.Blazor.Server/API/FileController.cs

C#
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;


namespace MySolution.Blazor.Server.API;


[Route("api/[controller]")]
[ApiController]
[Authorize]
public class FileController : ControllerBase {


    [HttpGet(nameof(Download))]
    public IActionResult Download(string fileName) {


        // Replace this line with an actual stream, e.g. file stream File.OpenRead(filePath);
        var stream = new MemoryStream(Encoding.UTF8.GetBytes("YourData"));
        return File(stream, "text/plain", fileName);
    }
}

Note
You must use the Authorize attribute in projects with the XAF Security System. For more information, refer to the following topic: Create Custom Endpoints.

在使用XAF安全系统的项目中,你必须使用Authorize特性。有关更多信息,请参阅以下主题:创建自定义终结点。
In projects without the XAF Security System, remove this attribute from code.
在没有XAF安全系统的项目中,从代码中删除此特性。

3.If your project includes an authorization setting (AddAuthorization or AddAuthorizationBuilder), use the CookieAuthenticationDefaults.AuthenticationScheme setting to allow cookies in the project. The back-end can then use cookies to authorize download requests initiated by the Blazor application. For more endpoint-related notes, refer to the corresponding section below.
如果您的项目包含授权设置(AddAuthorization 或 AddAuthorizationBuilder),请使用 CookieAuthenticationDefaults.AuthenticationScheme 设置来允许项目中使用 cookie。然后,后端可以使用 cookie 对 Blazor 应用程序发起的下载请求进行授权。有关更多与终结点相关的说明,请参阅下面的相应部分。

To enable cookies, modify the ConfigureServices method in the YourSolutionName.Blazor.Server/Startup.cs file as follows:
若要启用 cookie,请按如下方式修改 YourSolutionName.Blazor.Server/Startup.cs 文件中的 ConfigureServices 方法:

C#
namespace YourSolutionName.Blazor.Server;


public class Startup {
    // ...
    public void ConfigureServices(IServiceCollection services) {
        // ...
        services.AddAuthorizationBuilder()
            .SetDefaultPolicy(new AuthorizationPolicyBuilder(
                JwtBearerDefaults.AuthenticationScheme, CookieAuthenticationDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser()
                    .RequireXafAuthentication()
                    .Build());
        });
}

4.Add a new file (DownloadFileController.cs) with a View Controller to your Blazor project.
在你的Blazor项目中添加一个新文件(DownloadFileController.cs),其中包含一个视图控制器。

This controller adds a Download a File action to your application. When a user clicks the action, the application passes the fileContent value to the browser as a file.
此控制器会向您的应用程序添加“下载文件”操作。当用户点击该操作时,应用程序会将 fileContent 值作为文件传递给浏览器。

C#
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp;
using DevExpress.Persistent.Base;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;


namespace YourSolutionName.Blazor.Server.Controllers;


public partial class DownloadFileController : ViewController {


    public DownloadFileController() {
        var downloadAction = new SimpleAction(this, "Download a File", PredefinedCategory.Save);


        downloadAction.Execute += async (s, e) => {
            IJSRuntime jsRuntime = Application.ServiceProvider.GetRequiredService<IJSRuntime>();
            NavigationManager navigationManager = Application.ServiceProvider.GetRequiredService<NavigationManager>();
            var fileName = "Test.txt";
            var fileURL = $"{navigationManager.BaseUri}api/File/Download?fileName={fileName}";
            await jsRuntime.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);
        };
    }
}

5.Run the application and click Download a File. The specified file is downloaded to the browser.
运行应用程序并点击“下载文件”。指定的文件将下载到浏览器中。

在这里插入图片描述

Endpoint-Related Notes(端点相关说明)

  • XAF Blazor already has an API endpoint that can return data from the File Attachment module’s IFileData objects. If your task uses files attached to Business Objects, you can use the {navigationManager.BaseUri}IFileUrlService/?objectType= MySolution.Module.BusinessObjects.Resume&objectKey=1dc9dfd3-7389-4e17-930c-c4018deb4acc&propertyName=File URL pattern instead of implementing your own API controller.
    XAF Blazor已经有一个API端点,它可以从文件附件模块的IFileData对象返回数据。如果您的任务使用附加到业务对象的文件,您可以使用{navigationManager.BaseUri}IFileUrlService/?objectType= MySolution.Module.BusinessObjects.Resume&objectKey=1dc9dfd3-7389-4e17-930c-c4018deb4acc&propertyName=File这种URL模式,而不是实现自己的API控制器。

  • If you use an XAF Blazor project with Web API (Integrated Mode), you can also use the XAF Web API MediaFile/DownloadStream endpoint that returns data from the File Attachment module’s IFileData objects. This service has similar functionality to IFileUrlService mentioned before but offers more customization options. We recommend that you use this endpoint if you use Web API in your project. In this case, use the following URL pattern: {navigationManager.BaseUri}api/MediaFile/DownloadStream?objectType=Employee&objectKey=0eb531f9-2195-49e4-60b1-08db8ba8ed44&propertyName=Photo.
    如果您在XAF Blazor项目中使用Web API(集成模式),还可以使用XAF Web API的MediaFile/DownloadStream端点,该端点从文件附件模块的IFileData对象返回数据。此服务具有与前面提到的IFileUrlService类似的功能,但提供了更多自定义选项。如果您的项目中使用Web API,建议使用此端点。在这种情况下,请使用以下URL模式:{navigationManager.BaseUri}api/MediaFile/DownloadStream?objectType=Employee&objectKey=0eb531f9-2195-49e4-60b1-08db8ba8ed44&propertyName=Photo。

For more information about this endpoint, refer to the following topic: Obtain BLOB Data from a Web API Controller Endpoint.
有关此终结点的更多信息,请参阅以下主题:从Web API控制器终结点获取BLOB数据。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汤姆•猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值