Asp.net 下載功能的解決方案

來源:互聯網
上載者:User

1. 首先建立一個用於進行下載處理的page頁,如download.aspx,裡面什麼東西也沒有。
2. 添加一個DownloadHandler類,它繼承於IHttpHandler介面,可以用來自訂HTTP 處理常式同步處理HTTP的請求。 複製代碼 代碼如下: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; }
}
}

3. 這裡涉及到一個檔案名稱加解密的問題,是為了防止檔案具體名稱暴露在狀態列中,所以添加一個FileHelper類,代碼如下: 複製代碼 代碼如下: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);
}
}

利用Base64碼對檔案名稱進行加解密處理。
4. 在Web.config上,添加httpHandlers結點,如下: 複製代碼 代碼如下:<system.web>
<httpHandlers>
<add verb="*" path="download.aspx" type="DownloadHandler" />
</httpHandlers>
</system.web>

5. 現在建立一個aspx頁面,對檔案進行下載:
Default.aspx代碼如下:
Default.aspx 複製代碼 代碼如下:<%@ 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>檔案下載</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 複製代碼 代碼如下: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;
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.