最近有需求須要下載文件,多是image的圖片,也多是pdf報告,也多是微軟的word或者excel文件。web
這裏就整理了asp.net mvc 和asp.net webapi 下載的方法api
在mvc中,control的returnresult有FileResult,描述以下:mvc
System.Web.Mvc.FileResult
System.Web.Mvc.FileContentResult
System.Web.Mvc.FilePathResult
System.Web.Mvc.FileStreamResult
下載的時候,由於要根據文件來設置其MimiType,若是是NET 4.5則可能使用一下代碼:app
MimeMapping.GetMimeMapping(fileName)
準備完畢只好,一下就是controller下載的方法:asp.net
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)); }
webapi的下載和mvc不太同樣,webapi須要設置返回的header等一系列屬性:spa
[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; }
總結
以上就是下載的一些我的總結。參考資料以下:.net
https://stackoverflow.com/questions/3604562/download-file-of-any-type-in-asp-net-mvc-using-fileresultexcel
https://stackoverflow.com/questions/26038856/how-to-return-a-file-filecontentresult-in-asp-net-webapicode