技术开发 频道

ASP.NET MVC通过FileResult发送文件

    【IT168 技术文档】在 Controller 中我们可以使用 FileResult 向客户端发送文件。

  FileResult

ASP.NET MVC通过FileResult发送文件
 

  FileResult 是一个抽象类,继承自 ActionResult。在 System.Web.Mvc.dll 中,它有如上三个子类,分别以不同的方式向客户端发送文件。

  在实际使用中我们通常不需要直接实例化一个 FileResult 的子类,因为 Controller 类已经提供了六个 File 方法来简化我们的操作:

protected internal FilePathResult File(string fileName, string contentType);
protected internal virtual FilePathResult File(
string fileName, string contentType, string fileDownloadName);
protected internal FileContentResult File(
byte[] fileContents, string contentType);
protected internal virtual FileContentResult File(
byte[] fileContents, string contentType, string fileDownloadName);
protected internal FileStreamResult File(Stream fileStream,
string contentType);
protected internal virtual FileStreamResult File(Stream fileStream,
string contentType, string fileDownloadName);

 

  FilePathResult

  FilePathResult 直接将磁盘上的文件发送至浏览器:

  1. 最简单的方式

public ActionResult FilePathDownload1()
{
    var path
= Server.MapPath("~/Files/鹤冲天.zip");
    return File(path,
"application/x-zip-compressed");
}

 

  第一个参数指定文件路径,第二个参数指定文件的 MIME 类型。

  用户点击浏览器上的下载链接后,会调出下载窗口:

ASP.NET MVC通过FileResult发送文件
 

  大家应该注意到,文件名称会变成 Download1.zip,默认成了 Action 的名字。我们使用 File 方法的第二个重载来解决文件名的问题:

  2. 指定 fileDownloadName

public ActionResult FilePathDownload2()
{
    var path
= Server.MapPath("~/Files/鹤冲天.zip");
    return File(
"g:\\鹤冲天.zip", "application/x-zip-compressed", "crane.zip");
}

public ActionResult FilePathDownload3()
{
    var path
= Server.MapPath("~/Files/鹤冲天.zip");
    var name
= Path.GetFileName(path);
    return File(path,
"application/x-zip-compressed", name);
}

 

  我们可以通过给 fileDownloadName 参数传值来指定文件名,fileDownloadName 不必和磁盘上的文件名一样。下载提示窗口分别如下:

ASP.NET MVC通过FileResult发送文件
 

0
相关文章