您的位置:首页 > 编程语言 > ASP

ASP.Net MVC 之FileResult

2016-01-18 14:13 531 查看
FileResult是一个基于文件的ActionResult,利用FileResult我们可以很容易地将从某个物理文件的内容响应给客户端。ASP.NET MVC定义了三个具体的FileResult,分别是FileContentResult、FilePathResult和FileStreamResult。在这篇文章中我们将探讨三种具体的FileResult是如何将文件内容对请求进行响应的。[本文已经同步到《How ASP.NET MVC Works?》中]


目录
一、FileResult
二、FileContentResult
三、FilePathResult
四、FileStreamResult
五、实例演示:通过FileResult发布图片


一、FileResult

如下面的代码片断所示,FileResult具有一个表示媒体类型的只读属性ContentType,该属性在构造函数中被初始化。当我们基于某个物理文件创建相应的FileResult对象的时候应该根据文件的类型指定媒体类型,比如说目标文件是一个.jpg图片,那么对应的媒体类型为“image/jpeg”,对于一个.pdf文件,则采用“application/pdf”。

[code]public abstract class FileResult : ActionResult
{
//其他成员
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = this.ContentType;
if (!string.IsNullOrEmpty(this.FileDownloadName))
{
//生成Content-Disposition响应报头值
string headerValue = ContentDispositionUtil.GetHeaderValue(this.FileDownloadName);
context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);
}
this.WriteFile(response);
}
}

[/code]

[/code]

ASP.NET MVC定义了三个具体的FileResult,分别是FileContentResult、FilePathResult和FileStreamResult,接下来我们对它们进行单独介绍。

二、FileContentResult

FileContentResult是针对文件内容创建的FileResult。如下面的代码片断所示,FileContentResult具有一个字节数组类型的只读属性FileContents表示响应文件的内容,该属性在构造函数中指定。FileContentResult针对文件内容的响应实现也很简单,从如下所示的WriteFile方法定义可以看出,它只是调用当前HttpResponse的OutputStream属性的Write方法直接将表示文件内容的字节数组写入响应输出流。

[code]public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

public ActionResult Image(string id)
{
string path = Server.MapPath("/images/" + id + ".jpg");
return File(path, "image/jpeg");
}
}

[/code]
[/code]

图片的发布体现在Action方法Image上,表示图片ID的参数同时作为图片的文件名(不含扩展名)。在该方法中,我们根据图片ID解析出对应文件的路径后,直接调用File方法创建一个媒体类型为“image/jpeg”的FilePathResult。在Action方法Index中呈现的View定义如下,我们通过一个列表显示6张图片。基于图片的<img>元素的src属性指定的地址正是指向定义在HomeController的Action方法Image,指定的表示图片ID的参数分别是001、002、…、006。

[code]

[code]<html>
<head>
<title>Gallery</title>
<style type = "text/css" >
li{list-style-type:none; float:left; margin:10px 10px 0px 0px;}
img{width:100px; height:100px;}
</style>
</head>
<body>
<ul>
<li><img alt = "001" src="@Url.Action("Image", new { id = "001" })"/></li>
<li><img alt = "002" src="@Url.Action("Image", new { id = "002" })"/></li>
<li><img alt = "003" src="@Url.Action("Image", new { id = "003" })"/></li>
<li><img alt = "004" src="@Url.Action("Image", new { id = "004" })"/></li>
<li><img alt = "005" src="@Url.Action("Image", new { id = "005" })"/></li>
<li><img alt = "006" src="@Url.Action("Image", new { id = "006" })"/></li>
</ul>
</body>
</html>

[/code]
[/code]

我们将6张.jpg图片存放到/imges目录下,并分别命名为001、002、…、006。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: