1. 程式人生 > >Asp.net mvc 下載文件

Asp.net mvc 下載文件

設置 var value public ppa response oot turn cat

前言

最近有需求需要下載文件,可能是image的圖片,也可能是pdf報告,也可能是微軟的word或者excel文件。

這裏就整理了asp.net mvc 和asp.net webapi 下載的方法

ASP.NET MVC 下載

在mvc中,control的returnresult有FileResult,描述如下:

System.Web.Mvc.FileResult
      System.Web.Mvc.FileContentResult
      System.Web.Mvc.FilePathResult
      System.Web.Mvc.FileStreamResult

下載的時候,因為要根據文件來設置其MimiType,如果是NET 4.5則可能使用一下代碼:

MimeMapping.GetMimeMapping(fileName)

準備完畢只好,一下就是controller下載的方法:

public FileResult MyFile()
{
    string root = Server.MapPath("~/App_Data");
    string fileName = "test.jpg";
    string filePath = Path.Combine(root, fileName);
    string
s= MimeMapping.GetMimeMapping(fileName); return File(filePath, s, Path.GetFileName(filePath)); }

asp.net webapi 下載

webapi的下載和mvc不太一樣,webapi需要設置返回的header等一系列屬性:

[HttpGet]
public HttpResponseMessage Get(string name)
{
    var root = System.Web.HttpContext.Current.Server.MapPath("
~/App_Data"); string fileName = name; string path = Path.Combine(root, fileName); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName; //result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName)); result.Content.Headers.ContentLength = stream.Length; return result; }

總結

以上就是下載的一些個人總結。參考資料如下:

https://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresult

https://stackoverflow.com/questions/26038856/how-to-return-a-file-filecontentresult-in-asp-net-webapi

Asp.net mvc 下載文件