MVC&WebForm對照學習:檔案下載

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   color   os   ar   使用   

說完了WebForm和MVC中的檔案上傳,就不得不說使用者從伺服器端下載資源了。那麼今天就扯扯在WebForm和MVC中是如何?檔案下載的。說起WebForm中的檔案上傳,codeshark在他的博文ASP.NET實現檔案下載中講到了ASP.NET中檔案下載的4種方式。當然文章主要指的是在WebForm中的實現方式。總結得相當到位,那麼這篇,就先來看看MVC中檔案上傳的方式。然後再回過頭來看看它們實現方式的關聯。

Part 1 MVC中的檔案下載

在mvc中微軟封裝好了ActionResult的諸多的實現,這使我們根據需要靈活地選擇操作結果來響應使用者的操作。這其中一個很重要的實現就是.NET Framework 4.0中的FileResult。它表示一個用於將二進位檔案內容發送到響應的基類。FileResult類有三個實現:FileContentResult、FileStreamResult、FilePathResult。mvc中的檔案下載就是依賴這三個子類。不扯閑,先來看具體實現。

 FileContentResult

public ActionResult FileDownLoad(){    FileStream fs = new FileStream(Server.MapPath("~/uploads/Desert.jpg"), FileMode.Open, FileAccess.Read);    byte[] bytes = new byte[fs.Length];    fs.Read(bytes, 0, Convert.ToInt32(bytes.Length));    return File(bytes, "image/jpeg", "Desert.jpg");}

 FileStreamResult

public ActionResult FileDownLoad(){    return File(new FileStream(Server.MapPath("~/uploads/Desert.jpg"), FileMode.Open, FileAccess.Read), "image/jpeg", "Desert.jpg");}

 FilePathResult

public ActionResult FileDownLoad(){    return File(Server.MapPath("~/uploads/Desert.jpg"), "image/jpeg", "Desert.jpg");

看了上面的代碼是不是感覺這似乎比codeshark文章中講到的WebForm中的檔案下載代碼更簡潔了?確實!那麼我們同時也不禁要問:不是說mvc中的檔案下載依賴於FileContentResult、FilePathResult、FileStreamResult嗎,為什麼這裡邊無一例外都是return File(......)呢?這個對於接觸過mvc的你來說,相信難不倒你,F12一下就全明白了:

(圖1-1)

原來File(......)方法的背後返回的是FileContentResult、FileStreamResult、FilePathResult的執行個體。這就不足為怪了。那麼也就是說其實上面的3鐘實現方式你完全可以改成如下形式:

//FilePathResultreturn new FilePathResult(Server.MapPath("~/uploads/Desert.jpg"), "image/jpeg") { FileDownloadName = "Desert.jpg" };//FileStreamResultreturn new FileStreamResult(new FileStream(Server.MapPath("~/uploads/Desert.jpg"), FileMode.Open, FileAccess.Read), "image/jpeg") { FileDownloadName = "Desert.jpg" };//FileContentResultreturn new FileContentResult(System.IO.File.ReadAllBytes(Server.MapPath("~/uploads/Desert.jpg")), "image/jpeg") { FileDownloadName = "Desert.jpg" };

如果你通過ILSpay查看源碼的話,你會發現其實對應的return File(......)的內部實現就是如此。

問題1:不給fileDownloadNane賦值效果會如何

回過頭來再看1-1,我們還會發現FileContentResult、FileStreamResult、FilePathResult的下載方法,還各自對應的存在一個沒有第三個參數fileDownloadNane的方法重載。那麼這個方法又是用來幹嘛呢?小段代碼看下便知:

public ActionResult FileDownLoad(){    return File(Server.MapPath("~/uploads/Desert.jpg")}

--------------------------------------------------------------------------------運行結果-------------------------------------------------------------------------------------------------------------------

通過運行結果一眼就能看出,此時將圖片直接輸出在頁面上,這實現圖片的顯示功能。那麼同時我們也能夠知道,同樣的這樣也是可以的:

return new FilePathResult(Server.MapPath("~/uploads/Desert.jpg"), "image/jpeg") ;

問題2:加不加fileDownloadNane背後到底做了什麼

當然其它兩種方式同樣如此。那麼我們不禁要問:為什麼給不給fileDownloadName賦值,實現的效果完全不一樣呢?那麼你肯定想到了在內部肯定做了什麼來加以區分。那麼就以FilePathResult為例,用ILSpy來看看究竟:

(圖1-2)

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

(圖1-3)

先看圖1-2在FileResult類中有一個FileDownloadName公開屬性,我們知道ActionResult類最終要執行子類的ExecuteResult方法,而在FileResult的ExecuteResult方法中,對FileDownloadName進行了非空判斷。如果不為空白則通過Response.AddHeader()方法向用戶端瀏覽器傳送檔案。如果為空白則調用子類FilePathResult的重寫方法WriteFile() (圖1-3所示)直接向頁面輸出響應流。當然FileContentResult、FileStreamResult道理相同。

問題3:FileContentResult、FileStreamResult、FilePathResult檔案下載的方式到底有什麼不同

嗯,要回答這個問題,不用說,還是得看看它的內部實現。那麼我們就一個個地來看看究竟。

圖1-2和圖1-3種已經看得很清楚,最終檔案下載時指定了FileResult的ExecuteResult方法,而在ExecuteResult方法中調用了FileResult的子類的WriteFile方法。那麼我只需要查看每個子類的WriteFile方法便知道了。

FileContentResult

FileStreamResult

FilePathResult

再去看看codeshark的文章ASP.NET實現檔案下載,在這篇文章中他總結了檔案下載的4種方式:

方式一:TransmitFile實現下載。將指定的檔案直接寫入 HTTP 響應輸出資料流,而不在記憶體中緩衝該檔案。

方式二:WriteFile實現下載,將指定的檔案直接寫入 HTTP 響應輸出資料流。注意:對大型檔案使用此方法時,調用此方法可能導致異常。可以使用此方法的檔案大小取決於 Web 服務器的硬體設定。

方式三:WriteFile分塊下載

方式四:Response.BinaryWrite()流方式下載

那麼與mvc中檔案下載對照一下,不難發現,FilePathResult實際上是採用的Response.TransmitFile的方式實現下載的;而FileStreamResult是採用的WriteFile分區下載;FileContentResult在文章中沒有直接的對照方式,而它採用的是Response.OutputStream.Write的方式。另外Response.BinaryWrite()流的方式在mvc中沒有實現。當然在msdn上給出了實現我直接貼出實現代碼:

實現代碼:

public class BinaryContentResult : ActionResult{    public BinaryContentResult()    {    }    // Properties for encapsulating http headers.    public string ContentType { get; set; }    public string FileName { get; set; }    public byte[] Content { get; set; }    // The code sets the http headers and outputs the file content.    public override void ExecuteResult(ControllerContext context)    {        context.HttpContext.Response.ClearContent();        context.HttpContext.Response.ContentType = ContentType;        context.HttpContext.Response.AddHeader("content-disposition",             "attachment; filename=" + FileName);        context.HttpContext.Response.BinaryWrite(Content);        context.HttpContext.Response.End();    }}

調用代碼:

public ActionResult Download(string fn){    // Check whether the requested file is valid.    string pfn = Server.MapPath("~/App_Data/download/" + fn);    if (!System.IO.File.Exists(pfn))    {        throw new ArgumentException("Invalid file name or file not exists!");    }    // Use BinaryContentResult to encapsulate the file content and return it.    return new BinaryContentResult()    {        FileName = fn,        ContentType = "application/octet-stream",        Content = System.IO.File.ReadAllBytes(pfn)    };}

問題4:那麼FileContentResult的Response.OutputStream.Write()和Response.WriteFile()又有什麼區別昵

 關於這個問題,我查了很久,沒有得到比較滿翼的答案,在這裡希望大神指點一二!

Part 2 WebForm中的檔案下載

看看這篇文章ASP.NET實現檔案下載一目瞭然。四種方式不多說了。到這裡,不得不說MVC中的檔案下載is so easy!這還得歸功於微軟的封裝。那麼問題來了,在WebForm中我們是不是因該也封裝一個這樣的實現,這樣在以後使用的時候不用寫(當然一般是copy)重複寫這麼寫這些容易忘記的代碼了昵? Of course, just do it! 網上我沒有找到一個針對這個實現的封裝(有大神代碼可以貢獻一下)。我索性自己寫一個,好不好,就不說了。

1.定義抽象類別

先定義一個抽象列FileDownloader,定義公用的下載行為WriteFile方法和執執行下載的Execute方法以及檔案下載名_fileDownloadName。代碼如下:

public abstract class FileDownloader{    private string _fileDownloadName;    public FileDownloader(string contentType)    {        if (string.IsNullOrEmpty(contentType))        {            throw new ArgumentException("contentType");        }        this.ContentType = contentType;    }    public void Execute(HttpContext context)    {        if (context == null)        {            throw new ArgumentNullException("context");        }        HttpResponse response = context.Response;        response.ClearContent();        response.ContentType = this.ContentType;        if (!string.IsNullOrEmpty(this.FileDownloadName))        {            context.Response.AddHeader("content-disposition",            "attachment; filename=" + this.FileDownloadName);        }        this.WriteFile(context.Response);        response.Flush();        response.End();    }    protected abstract void WriteFile(HttpResponse response);    public string ContentType { get; private set; }    public string FileDownloadName    {        get        {            return (this._fileDownloadName ?? string.Empty);        }        set        {            this._fileDownloadName = value;        }    }}

2.建立實作類別

此處類比MVC中的實現方式建立對應的WebForm中的實現方式,為了易於區分說明,我採取和MVC中同樣的類名。

MVC中FileContentResult的下載方式(區別於FileStreamResult分區下載),這裡實現一下:

public class FileContentResult : FileDownloader{    public FileContentResult(byte[] fileContents, string contentType)        : base(contentType)    {        if (fileContents == null)        {            throw new ArgumentNullException("fileContents");        }        this.FileContents = fileContents;    }    public byte[] FileContents { get; private set; }    protected override void WriteFile(HttpResponse response)    {        response.OutputStream.Write(this.FileContents, 0, this.FileContents.Length);    }}

 FileStreamResult(分區下載):

public class FileStreamResult : FileDownloader{    public FileStreamResult(Stream fileStream, string contentType)        : base(contentType)    {        if (fileStream == null)        {            throw new ArgumentNullException("fileStream");        }        this.FileStream = fileStream;    }    public Stream FileStream { get; private set; }    protected override void WriteFile(HttpResponse response)    {        Stream outputStream = response.OutputStream;        using (this.FileStream)        {            byte[] buffer = new byte[4096];            while (true)            {                int num = this.FileStream.Read(buffer, 0, 4096);                if (num == 0)                {                    break;                }                outputStream.Write(buffer, 0, num);            }        }    }}

FIlePathResult:

public class FIlePathResult : FileDownloader{    public FIlePathResult(string fileName, string contentType)        : base(contentType)    {        if (string.IsNullOrEmpty(fileName))        {            throw new ArgumentNullException("fileName");        }        this.FileName = fileName;    }    public string FileName { get; private set; }    protected override void WriteFile(HttpResponse response)    {        response.TransmitFile(this.FileName);    }}

另外上面我們也採用了微軟上BinaryContentResult的實現,這裡同樣也實現一下BinaryContentResult:

public class BinaryContentResult : FileDownloader{    public BinaryContentResult(byte[] fileContents, string contentType)        : base(contentType)    {        if (fileContents == null)        {            throw new ArgumentNullException("fileContents");        }        this.FileContents = fileContents;    }    protected override void WriteFile(HttpResponse response)    {        response.BinaryWrite(FileContents);    }    public byte[] FileContents { get; private set; }}

另外還有HttpResponse.WriteFile(net 2.0中的提出的,對大型檔案使用此方法時,調用此方法可能會引發異常這裡姑且稱之為舊的實現方式:

public class FilePathOldResult : FileDownloader{    public FilePathOldResult(string fileName, string contentType)        : base(contentType)    {        if (string.IsNullOrEmpty(fileName))        {            throw new ArgumentNullException("fileName");        }        this.FileName = fileName;    }    public string FileName { get; private set; }    protected override void WriteFile(HttpResponse response)    {        response.WriteFile(this.FileName);    }

Part 3 問題開發

在檔案下載中,我們可能需要自動擷取檔案的MIME類型,這在指定檔案的下載類型時。那麼如何擷取檔案的MIME類型呢?在Mitchell Chu的部落格.NET擷取檔案的MIME類型(Content Type)中給出了比較好的答案。這裡就不做贅述。

Part 4 The end

回過頭來看還是那句話,因為MVC和WebForm都是基於ASP.NET架構,因此檔案下載功能的背後還是採用了相同的組件實現。

註:由於個人技術有限,對某些概念的理解可能會存在偏差,如果你發現本文存在什麼bug,請指正。謝謝!

完。

 

MVC&WebForm對照學習:檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.