Objective
Recently there is a need to download a file, possibly an image of an image, a PDF report, or a Microsoft Word or Excel file.
Here we have compiled the methods of ASP. NET MVC and ASP. NET Webapi Download
ASP. NET MVC Download
In MVC, the returnresult of control has Fileresult, which is described as follows:
System.Web.Mvc.FileResult System.Web.Mvc.FileContentResult System.Web.Mvc.FilePathResult System.Web.Mvc.FileStreamResult
When downloading, because you want to set its mimitype according to the file, if it is net 4.5 then you may use the code:
Mimemapping.getmimemapping (FileName)
Ready to go, the controller is the way to download:
Public Fileresult MyFile () { string root = Server.MapPath ("~/app_data" ); string " test.jpg " ; string FilePath = path.combine (root, FileName); string s= mimemapping.getmimemapping (fileName); return File (FilePath, S, Path.getfilename (FilePath));}
ASP. Webapi Download
Webapi download and MVC are not the same, Webapi need to set a series of properties such as the return header:
[HttpGet] PublicHttpresponsemessage Get (stringname) { varRoot = System.Web.HttpContext.Current.Server.MapPath ("~/app_data"); stringFileName =name; stringPath =Path.Combine (root, FileName); Httpresponsemessage result=Newhttpresponsemessage (Httpstatuscode.ok); varstream =NewFileStream (path, FileMode.Open); Result. Content=NewStreamcontent (stream); Result. Content.Headers.ContentDisposition=NewContentdispositionheadervalue ("Attachment"); Result. Content.Headers.ContentDisposition.FileName=FileName; //result. Content.Headers.ContentType = new Mediatypeheadervalue ("Application/octet-stream");Result. Content.Headers.ContentType =NewMediatypeheadervalue (mimemapping.getmimemapping (fileName)); Result. Content.Headers.ContentLength=Stream. Length; returnresult;}
总结
The above is the download of some personal summary. The resources are as follows:
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 download file