文章出處

上一篇 介紹了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, 但是主要的部分都是差不多的.


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()