MVC File Download

Source: Internet
Author: User

Method 1:

/// <Summary>

/// File Download class
/// Call 1: downloadfile ("/2003.xls", null );
/// Call 2: downloadfile ("/2003.xls ","");
/// Call 3: downloadfile ("/2003.xls"," temp.xls ");
/// </Summary>
/// <Param name = "filepath"> file path (Format:/upload/2003.xls) </param>
/// <Param name = "FILENAME"> Custom file name (if you do not want to customize a file name, upload ["" or null]) </param>

Public actionresult downfile (string filepath, string filename)

  1. {
  2. Filepath = server. mappath (system. configuration. configurationmanager. deleetpipeline ["attachmentpath"] + filepath );
  3. Filestream FS = new filestream (filepath, filemode. Open );
  4. Byte [] bytes = new byte [(INT) fs. Length]; // download an object as a response stream

  5. FS. Read (bytes, 0, bytes. Length );
  6. FS. Close ();
  7. Response. charset = "UTF-8 ";
  8. Response. contentencoding = system. Text. encoding. getencoding ("UTF-8 ");
  9. Response. contenttype = "application/octet-stream"; // notify the browser to download the file instead of opening it

  10. Response. addheader ("content-disposition", "attachment; filename =" + server. urlencode (filename ));
  11. Response. binarywrite (bytes );
  12. Response. Flush ();
  13. Response. End ();
  14. Return new emptyresult ();
  15. }

Method 2:

Public filestreamresult downfile (string filepath, string filename)
{
String absolufilepath = server. mappath (system. configuration. configurationmanager. deleettings ["attachmentpath"] + filepath );
Return file (New filestream (absolufilepath, filemode. Open), "application/octet-stream", server. urlencode (filename ));
}

Call method:

<A href = "/document/downfile? Filepath = @ item. Value & filename = @ item. Key "> download </a>

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.