MVC returns a file. mvc returns

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.