惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
V
V2EX
博客园 - 聂微东
The Cloudflare Blog
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
博客园 - 司徒正美
H
Help Net Security
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
V
Visual Studio Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
Y
Y Combinator Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
F
Fortinet All Blogs
B
Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园_首页
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
量子位
I
InfoQ
小众软件
小众软件
P
Proofpoint News Feed

博客园 - vito qi

安装VS2015出现的bug,各位安装请注意 苹果编程语言Swift简介 设计模式之三职责链模式 HTML页面做中间页跳转传递参数 第一个 ASP.NET Web API应用程序 ASP.NET MVC中 Jquery AJAX 获取数据利用MVC模型绑定实现输出 ASP.NET应用程序与页面生命周期 自定义服务器控件ImageButton 成功项目经理的三种领导力行为 设计模式之二抽象工厂设计模式 深入理解C#之 参数传递 ref out params C#实现根据IP 查找真实地址 IIS 7.0的集成模式和经典模式 ASP.NET 4.0: 请求验证模式变化导致ValidateRequest=false失效 设计模式之—简单工厂设计模式 ASP.NET MVC 学习笔记(一) 数据库分离附加工具 c# 新特性 c#总结(一)
ASP.NET 实现文件下载
vito qi · 2012-06-12 · via 博客园 - vito qi

在日常项目中,我们经常用到文件的上传下载功能,今天分享一个在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);