Button events directly download any file format

Source: Internet
Author: User

 

# Region -- download file button event -----------------

String FullFileName = Server. Mappath ("~ /"+" Relative path of the file to be downloaded ")
String strFileName = FullFileName. Substring (FullFileName. LastIndexOf ("/") + 1); // get the file name (excluding the path)

FileInfo DownloadFile;
Try
{
DownloadFile = new FileInfo (FullFileName); // you can specify the object to be downloaded.

Response. Clear (); // Clear all content output in the buffer stream

Response. ClearHeaders (); // clear all headers in the buffer stream. If you do not write this statement, the error page is displayed.

Response. Buffer = false; // set the Buffer output to false.

// Set the http mime type of the output stream to application/octet-stream

Response. ContentType = "application/octet-stream ";

// Add the HTTP header to the output stream

Response. AppendHeader ("Content-Disposition ",

"Attachment; filename =" + strFileName + DownloadFile. Extension );

Response. AppendHeader ("Content-Length", DownloadFile. Length. ToString ());

// Write the specified file directly to the HTTP Content output stream.

// It must be noted that WriteFile is not a Write (it hurts me for one night)

Response. WriteFile (DownloadFile. FullName );

Response. Flush (); // send the Current Buffer output to the client

Response. End (); // sends all the current buffer output to the client. This user sometimes has an error. You can try to put this sentence in the last line of the entire function. You can also use HttpContext. Current. ApplicationInstance. CompleteRequest () instead.
}
Catch (Exception err)
{
// Handle errors
// This. labelStatus. Text = "unable to download file:" + sFileName + ", due to:" + err. Message;
}

# Endregion -- download file button event -----------------

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.