ASP.NET MVC 实现文件下载的多种方式

c程序员 by:c程序员 分类:C# 时间:2024/09/26 阅读:25 评论:0

ASP.NET MVC是一种基于 Model-View-Controller(模型-视图-控制器)架构的 Web 应用程序开发框架。在实际开发过程中,我们经常需要实现文件下载的功能,比如下载报表、导出数据等。本文将为您介绍在 ASP.NET MVC 中实现文件下载的多种方式。

1. 直接返回文件流

最简单的方式就是直接在控制器中返回文件流。我们可以通过 File() 方法来实现这一功能。示例代码如下:

```csharp public ActionResult DownloadFile() { string filePath = Server.MapPath("~/App_Data/example.pdf"); return File(filePath, "application/pdf", "example.pdf"); } ```

在上述代码中,我们首先获取文件的物理路径,然后使用 File() 方法返回文件流。该方法有三个参数:

  • filePath: 文件的物理路径
  • "application/pdf": 文件的 MIME 类型,这里以 PDF 文件为例
  • "example.pdf": 下载时显示的文件名

2. 使用 FileResult 返回文件

除了直接使用 File() 方法,我们还可以使用 FileResult 类型来返回文件。示例代码如下:

```csharp public FileResult DownloadFile() { string filePath = Server.MapPath("~/App_Data/example.pdf"); byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); return File(fileBytes, "application/pdf", "example.pdf"); } ```

在上述代码中,我们首先读取文件的字节数组,然后使用 File() 方法返回 FileResult 对象。这种方式相比直接使用 File() 方法更加灵活,可以对文件进行更多的操作。

3. 使用 FileContentResult 返回文件

除了 FileResult,我们还可以使用 FileContentResult 类型来返回文件。示例代码如下:

```csharp public FileContentResult DownloadFile() { string filePath = Server.MapPath("~/App_Data/example.pdf"); byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); return new FileContentResult(fileBytes, "application/pdf") { FileDownloadName = "example.pdf" }; } ```

在上述代码中,我们使用 FileContentResult 类型来返回文件。与 FileResult 不同的是,我们可以在构造函数中直接传入文件的字节数组和 MIME 类型,并通过 FileDownloadName 属性设置下载时显示的文件名。

4. 使用 ActionResult 返回

非特殊说明,本文版权归原作者所有,转载请注明出处

本文地址:https://chinaasp.com/2024097092.html


TOP