FileResult (可應用於網頁顯示圖片)

 

FileResult是一個抽象類別,但他被三個子類別所實現,分別是

FilePathResult、FileStreamResult、FileContentResult,

其功能最常用於讓使用者從伺服器下載檔案到自已的電腦上。

 

一、FilePathResult

有兩種多載方式

FilePathResult File(string fileName, string contentType);
FilePathResult File(string fileName, string contentType, string fileDownloadName);

範例為

public ActionResult Index()
{
    string path = Server.MapPath(@"~\Content\Site.css");
    return File(path, "application/css", "Site.css");
}

其結果會下載一份Site.css檔到電腦裡,如果想在瀏灠器直接觀看的話,應改為

public ActionResult Index()
{
    string path = Server.MapPath(@"~\Content\Site.css");
    return File(path, "text/html");
}

 

二、FileStreamResult

有兩種多載方式

FileStreamResult File(Stream fileStream, string contentType);
FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);

範例為

public ActionResult Index()
{
    string path = Server.MapPath(@"~\Content\Site.css");
    System.IO.FileStream fs = System.IO.File.OpenRead(path);
    return File(fs, "application/css", "Site.css");
}

 

三、FileContentResult

有兩種多載方式

FileContentResult File(byte[] fileContents, string contentType);
FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);

範例為

public ActionResult Index()
{
    System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~\pic.png"), System.IO.FileMode.Open);
    int length = (int)fs.Length;
    byte[] buffer = new byte[length];
    int count;
    int sum = 0;
    while ((count = fs.Read(buffer, sum, length - sum)) > 0)
        sum += count;
    fs.Close();
    return File(buffer, "image/png", "pic.png");
}

其結果會下載一份pic.png檔到電腦裡,如果想在瀏灠器直接觀看的話,應改為

public ActionResult Index()
{
    System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~\pic.png"), System.IO.FileMode.Open);
    int length = (int)fs.Length;
    byte[] buffer = new byte[length];
    int count;
    int sum = 0;
    while ((count = fs.Read(buffer, sum, length - sum)) > 0)
        sum += count;
    fs.Close();
    return File(buffer, "image/png");
}