之前作asp.net下載功能的時候都是採用:
<a href="http://www.wang0214.com/wgcms">下載</a>
的方式來實現下載。
但後來發現,這種方法存在諸多弊端。至於弊端緣由百度一下就明白了。
因此,下面分享下本身修改完善後,asp.net加密文件下載功能:html
不想看詳細介紹的直接點擊這裏下載:
開始下載:點擊下載
解壓密碼:www.wang0214.comweb
一、首先新建一個用於進行下載處理的page頁,如download.aspx,裏面不須要寫任何東西。app
二、新建一個DownloadHandler類,它繼承於IHttpHandler接口,能夠用來自定義HTTP 處理程序同步處理HTTP的請求。asp.net
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;
using System.Diagnostics;
using System.IO;
/// <summary>
///DownloadHandler 的摘要說明
///萬廣互聯(www.wang0214.com)
///專業品牌網站建設
/// </summary>
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"]); //經過解密獲得文件名
string filepath = 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; }
}
}網站
三、這裏涉及到一個文件名加解密的問題,是爲了防止文件具體名稱暴露在狀態欄中,因此添加一個FileHelper類,代碼以下:加密
using System;
using System.Collections.Generic;
using System.Web;
/// <summary>
///FileHelper 的摘要說明
/// </summary>
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);
}
}url
四、在Web.config上,添加httpHandlers結點,以下:.net
<system.web>
<httpHandlers>
<add verb="*" path="download.aspx" type="DownloadHandler" />
</httpHandlers>
</system.web>code
五、如今新建一個aspx頁面,對文件進行下載:
Default.aspx代碼以下:
Default.aspx Codeorm
<%@ 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 id="Head1" runat="server">
<title>文件下載</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HyperLink ID="link" runat="server" Text="文件下載"></asp:HyperLink>
</div>
</form>
</body>
</html>
Default.aspx.cs代碼以下:
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;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
//全局變量
private static object _SyncLockObject = new object();
protected void Page_Load(object sender, EventArgs e)
{
string url = FileHelper.Encrypt("萬廣互聯_深圳網站建設.jpg");
link.NavigateUrl = "~/download.aspx?fn=" + url;
}
}
經過以上詳解講解後,還不能領會的把,就下載下面的源代碼吧:
開始下載:點擊下載解壓密碼:www.wang0214.com