06/16 : Using Httphanlder to download different files
(1)Create a page with a link with download file path to another page download.aspx.
eg:
string url = (@"\\colpdm20\TIEMLCL Vaults\Released\00110-U1170-71-B.tif");
link.NavigateUrl = "~/download.aspx?fn=" + url;
(2). Create a empty download.aspx page
(3). Create Httphandler to handle downloading request
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 = Request["fn"];
//"52110-32960-71_843789_822.JPG";
//FileHelper.Decrypt(Request["fn"]); //通过解密得到文件名
string filepath = Request["fn"];
//@"\\colpdm20\TIEMLCL Vaults\Released\" + filename;
//HttpContext.Current.Server.MapPath("~/") + "files/" + filename; //待下载的文件路径
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(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; }
}
}
(4). Add following changes in web.config
<httpHandlers>
<add verb="*" path="download.aspx" type="DownloadHandler"/>
….
</httpHandlers>