SoFunction
Updated on 2025-04-08

Download function solution code

1. First create a new page for download processing, such as, there is nothing in it.
2. Add a DownloadHandler class, which inherits from the IHttpHandler interface, and can use a custom HTTP handler to synchronize HTTP requests.
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpResponse Response = ;
HttpRequest Request = ;
iStream = null;
byte[] buffer = new Byte[10240];
int length;
long dataToRead;
try
{
string filename = (Request["fn"]); //Get file name by decryption
string filepath = ("~/") + "files/" + filename; //The path to download
iStream = new (filepath, ,
, );
();
dataToRead = ;
long p = 0;
if (["Range"] != null)
{
= 206;
p = (["Range"].Replace("bytes=", "").Replace("-", ""));
}
if (p != 0)
{
("Content-Range", "bytes " + () + "-" + ((long)(dataToRead - 1)).ToString() + "/" + ());
}
("Content-Length", ((long)(dataToRead - p)).ToString());
= "application/octet-stream";
("Content-Disposition", "attachment; filename=" + ((65001).GetBytes((filename))));
= p;
dataToRead = dataToRead - p;
while (dataToRead > 0)
{
if ()
{
length = (buffer, 0, 10240);
(buffer, 0, length);
();
buffer = new Byte[10240];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
("Error : " + );
}
finally
{
if (iStream != null)
{
();
}
();
}
}
public bool IsReusable
{
get { return true; }
}
}
3. This involves a problem of file name encryption and decryption. In order to prevent the specific name of the file from being exposed to the status bar, a FileHelper class is added, and the code is as follows:
public class FileHelper
{
public static string Encrypt(string filename)
{
byte[] buffer = (filename);
return (Convert.ToBase64String(buffer));
}
public static string Decrypt(string encryptfilename)
{
byte[] buffer = Convert.FromBase64String(encryptfilename);
return (buffer);
}
}
The file name is encrypted and decrypted using Base64 code.
4. On, add the httpHandlers node as follows:
<>
<httpHandlers>
<add verb="*" path="" type="DownloadHandler" />
</httpHandlers>
</>
5. Now create a new aspx page and download the file:
The code is as follows:
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml" >
<head runat="server">
<title>File Download</title>
</head>
<body>
<form runat="server">
<div>
<asp:HyperLink ID="link" runat="server" Text="File Download"></asp:HyperLink>
</div>
</form>
</body>
</html>
The code is as follows:
Code
using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
public partial class _Default :
{
protected void Page_Load(object sender, EventArgs e)
{
string url = ("");
= "~/?fn=" + url;
}
}