揭秘asp.net 下载功能的实现

    技术2022-05-20  50

    看到好多的博文中介绍的asp.net的文件下载是用ASPX文件实现的,其实那样做是根本没必要的,甚至有的是时候会出现问题的,推荐用ashx文件,也就是一般处理程序。好吧废话不多说上代码

    using System;using System.Collections.Generic;using System.Linq;using System.Web;

    namespace FileDownload{/// <summary>/// Download 的摘要说明/// </summary>public class Download : IHttpHandler{

    public void ProcessRequest(HttpContext context){//添加一个文件的数据类型context.Response.ContentType = "application/octet-stream";//将文件名进行编码防止乱码string encodeFileName = HttpUtility.UrlEncode("要下载的文件名");//获得文件的全路径

    string filepath = context.Server.MapPath("服务器上的下载文件名");//添加一个报文头context.Response.AddHeader("Content-Disposition", "attachment;filename=" + encodeFileName);context.Response.AddHeader("Content-Length", encodeFileName.Length.ToString());

    context.Response.WriteFile(filepath );context.Response.End();}

    public bool IsReusable{get{return false;}}}}

    上面的方法是直接输出文件的方式实现的,对一般的文件来说足够了,但是如果是大文件的话我们的这种方法是不行的,应该使用FileStream的形式实现。方法和上面的方法一样,只不过改成了FileStream的形式输出。代码如下:

    using System;using System.Collections.Generic;using System.Linq;using System.Web;

    namespace FileDownload{/// <summary>/// Stream 的摘要说明/// </summary>public class Stream : IHttpHandler{

    public void ProcessRequest(HttpContext context){System.IO.Stream iStream = null;byte[] buffer = new Byte[10000];int length;long dataToRead;string filepath = 要下载文件的全路径;string encodeFileName = HttpUtility.UrlEncode("文件名");

    try{iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,System.IO.FileAccess.Read, System.IO.FileShare.Read);

    dataToRead = iStream.Length;

    context.Response.ContentType = "application/octet-stream";context.Response.AddHeader("Content-Disposition", "attachment; filename=" + encodeFileName);while (dataToRead > 0){if (context.Response.IsClientConnected){length = iStream.Read(buffer, 0, 10000);context.Response.OutputStream.Write(buffer, 0, length);context.Response.Flush();

    buffer = new Byte[10000];dataToRead = dataToRead - length;}else{dataToRead = -1;}}}catch (Exception ex){context.Response.Write("Error : " + ex.Message);}finally{if (iStream != null){iStream.Close();}}

    }

    public bool IsReusable{get{return false;}}}}

    由于时间问题鄙人就偷懒没有写注释了,基本和上面差不多。

    但有时甚至大多数情况下,只是单纯的提供一个下载是不够的我们要做一些下载权限的控制,说到控制大家肯定第一个想到的就是Session了,但是直接在Ashx文件中使用Session大家会发现会报错,这是怎么回事呢?

    ashx程序中操作Session要在类文件头后加IRequiresSessionState,

    引用using System.Web.SessionState;例子如下:

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.SessionState;

    namespace Login{/// <summary>/// Download 的摘要说明/// </summary>public class Download : IHttpHandler,IRequiresSessionState

    这样我们就可以像在aspx文件一样使用我们的context.Session[""]了。

    好了和大家聊了这么久,大家也累了吧,但是还是希望大家能自己实验一下,如有什么不对的或更好的可不要忘了告讼我呀!!!!


    最新回复(0)