Solution code for Asp.net download

Source: Internet
Author: User

1. Create a page for download processing, such as download. aspx. There is nothing in it.
2. Add a DownloadHandler class that inherits from the IHttpHandler interface. You can use a custom HTTP handler to synchronously process HTTP requests.
Public class DownloadHandler: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
HttpResponse Response = context. Response;
HttpRequest Request = context. Request;
System. IO. Stream iStream = null;
Byte [] buffer = new Byte [10240];
Int length;
Long dataToRead;
Try
{
String filename = FileHelper. Decrypt (Request ["fn"]); // obtain the file name through decryption
String filepath = HttpContext. Current. Server. MapPath ("~ /") +" Files/"+ filename; // path of the file to be downloaded
IStream = new System. IO. FileStream (filepath, System. IO. FileMode. Open,
System. IO. FileAccess. Read, System. IO. FileShare. Read );
Response. Clear ();
DataToRead = iStream. Length;
Long p = 0;
If (Request. Headers ["Range"]! = Null)
{
Response. StatusCode = 206;
P = long. Parse (Request. Headers ["Range"]. Replace ("bytes =", ""). Replace ("-",""));
}
If (p! = 0)
{
Response. addHeader ("Content-Range", "bytes" + p. toString () + "-" + (long) (dataToRead-1 )). toString () + "/" + dataToRead. toString ());
}
Response. AddHeader ("Content-Length", (long) (dataToRead-p). ToString ());
Response. ContentType = "application/octet-stream ";
Response. addHeader ("Content-Disposition", "attachment; filename =" + System. web. httpUtility. urlEncode (System. text. encoding. getEncoding (1, 65001 ). getBytes (Path. getFileName (filename ))));
IStream. Position = p;
DataToRead = dataToRead-p;
While (dataToRead> 0)
{
If (Response. IsClientConnected)
{
Length = iStream. Read (buffer, 0, 10240 );
Response. OutputStream. Write (buffer, 0, length );
Response. Flush ();
Buffer = new Byte [10240];
DataToRead = dataToRead-length;
}
Else
{
DataToRead =-1;
}
}
}
Catch (Exception ex)
{
Response. Write ("Error:" + ex. Message );
}
Finally
{
If (iStream! = Null)
{
IStream. Close ();
}
Response. End ();
}
}
Public bool IsReusable
{
Get {return true ;}
}
}
3. The file name encryption and decryption problem is involved here. To prevent the file name from being exposed to the status bar, add a FileHelper class. The Code is as follows:
Public class FileHelper
{
Public static string Encrypt (string filename)
{
Byte [] buffer = HttpContext. Current. Request. ContentEncoding. GetBytes (filename );
Return HttpUtility. UrlEncode (Convert. ToBase64String (buffer ));
}
Public static string Decrypt (string encryptfilename)
{
Byte [] buffer = Convert. FromBase64String (encryptfilename );
Return HttpContext. Current. Request. ContentEncoding. GetString (buffer );
}
}
Use Base64 to encrypt and decrypt the file name.
4. On Web. config, add the httpHandlers node as follows:
<System. web>
<HttpHandlers>
<Add verb = "*" path = "download. aspx" type = "DownloadHandler"/>
</HttpHandlers>
</System. web>
5. Create An aspx page to download the file:
The Default. aspx code is as follows:
Default. aspx Code
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> File Download </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: HyperLink ID = "link" runat = "server" Text = "File Download"> </asp: HyperLink>
</Div>
</Form>
</Body>
</Html>
The Default. aspx. cs code is as follows:
Default. aspx. cs Code
Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
String url = FileHelper. Encrypt ("DesignPattern. chm ");
Link. NavigateUrl = "~ /Download. aspx? Fn = "+ url;
}
}

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.