MVC returns a file. mvc returns
The previous article introduced Action returned View, and also saw the processing of returned Json. This article does not look at the source code returned by the file. This article is for application.
1. Response returned File
In the MVC project, we can still see many colleagues who prefer to use Response to return files. For example:
public void Index(){ var path = Server.MapPath("~/Content/Site.css"); using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0 , bytes.Length); fs.Close(); Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Site.css")); Response.AddHeader("Content-Length", bytes.Length.ToString()); Response.BinaryWrite(bytes); Response.Flush(); }}
After entering the address in the browser, the file will be downloaded directly.
Although this method can indeed return objects, it provides a simple method in MVC to return objects as return values.
2. FileResult
public ActionResult Get(){ var path = Server.MapPath("~/Content/Site.txt"); return File(new FileStream(path, FileMode.Open), "text/plain", HttpUtility.UrlEncode("Site.txt"));}
A contentType problem is involved when the file is returned. This contentType cannot be remembered, so it is also referenced here. You can check it during development.
I usually use these two methods. Of course, there are other methods. For example, MemoryStream can be used when an excel file is returned, but the main part is similar.