ASP.NET 实现文件下载

在日常项目中,我们经常用到文件的上传下载功能,今天分享一个在ASP.NET中下载文件的例子,通过实现IHttpHandler 来实现下载。

直接上代码:

DownloadHandler.cs

View Code
public class DownloadHandler:IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        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();
            }
        }
    }

FileHelper.cs

View Code
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);
        }
    }

在web.config的<handlers> 节点中添加

 <add name="download" verb="*" path="download.aspx" type="SinoOcean.Seagull2.Questionnaire.Common.DownloadHandler" />

path 下载页面的路径。

verb 谓词 请求的方式 http ftp get post 等。设置为* 代表所有。

type  类型 SinoOcean.Seagull2.Questionnaire.Common.DownloadHandler   SinoOcean.Seagull2.Questionnaire.Common 命名空间  DownloadHandler  类名

在项目中添加 download.aspx 页面 去掉后台代码文件 download.aspx.cs

aspx页面如下 :

View Code
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

在项目中创建一个文件夹 files

使用 下载功能:

                string url = FileHelper.Encrypt("文件名称");
                Response.Redirect("~/download.aspx?fn=" + url);

原文地址:https://www.cnblogs.com/suizhouqiwei/p/2545882.html