MVC返回文件

上一篇 介绍了Action 返回View, 顺便也看到了返回Json的处理, 这一篇并不看文件返回的源码, 此篇是为了应用.

1. Response返回文件

在MVC的项目中, 还是能看到很多同事, 喜欢使用 Response的方式来返回文件. 如:

public void Index()
{
    var path = Server.MapPath("~/Content/Site.css");
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0 , bytes.Length);
        fs.Close();

        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Site.css"));
        Response.AddHeader("Content-Length", bytes.Length.ToString());
        Response.BinaryWrite(bytes);

        Response.Flush();
    }
}

当在浏览器中直接输入地址后, 会直接下载这个文件.

虽然这种方式确实可以返回文件, 但是在MVC中, 提供了一个简便的方法. 可以把文件作为返回值去返回.

 

2. FileResult

public ActionResult Get()
{
    var path = Server.MapPath("~/Content/Site.txt");
    return File(new FileStream(path, FileMode.Open), "text/plain", HttpUtility.UrlEncode("Site.txt"));
}

 

返回文件的时候牵涉一个 contentType 的问题, 这个contentType, 我想没人能记得住, 所以这里也提出引用, 可以在开发的时候查看一下就可以了.

 一般的文件, 还可以通过  MimeMapping.GetMimeMapping("Site.txt") 的方式来获取类型. 

我常用的基本也就这两中了, 当然还有别的方式, 比如返回excel的时候, 可以使用MemoryStream, 但是主要的部分都是差不多的.

posted @ 2017-02-08 16:02  Sniper_ZL  阅读(1286)  评论(0编辑  收藏  举报