国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

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

2024-07-10 12:39:08
字體:
來源:轉載
供稿:網友
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" />
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿拉善左旗| 灌云县| 新丰县| 富平县| 涿鹿县| 中宁县| 略阳县| 哈尔滨市| 航空| 鞍山市| 拜泉县| 通江县| 宕昌县| 延安市| 鄂尔多斯市| 五指山市| 临沭县| 长丰县| 黄骅市| 古田县| 连平县| 阿城市| 普陀区| 乳山市| 青神县| 巩留县| 锦州市| 慈溪市| 海安县| 灵丘县| 卢龙县| 手游| 阜阳市| 石嘴山市| 巴东县| 宁蒗| 壶关县| 玉树县| 买车| 内丘县| 宿松县|