1,Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
Content-Disposition: attachment;filename=filename.ext
以上指令即标记此次响应流是附件,且附件文件名为 filename.ext
注意:
(1): 中文文件名需要进行URLEncode编码, 否则在IE 6 下会提示是”无法识别的文件”.

但经实际测试,在Chrome下不进行URLEncode编码, 也能正常显示.

(2): 文件名不能有空格, 否则也会被认为是”无法识别的文件”.

(3): [ASP.Net中] 向响应流中添加该指令必须使用 response.AddHeader() 函数; 使用

response.Header.Add() 则会报错.

下面是一个实现下载文件功能的函数:

/// <summary>
/// 使用微软的TransmitFile下载文件
/// </summary>
/// <param name="filePath">服务器相对路径</param>
public void TransmitFile(string filePath)
{
try
{
filePath = Server.MapPath(filePath);
if (File.Exists(filePath))
{
FileInfo info = new FileInfo(filePath);
long fileSize = info.Length;
HttpContext.Current.Response.Clear(); //指定Http Mime格式为压缩包
HttpContext.Current.Response.ContentType = "application/x-zip-compressed"; // Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
// Content-Disposition: attachment;filename=filename.txt
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(info.FullName));
//不指明Content-Length用Flush的话不会显示下载进度
HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
HttpContext.Current.Response.TransmitFile(filePath, , fileSize);
HttpContext.Current.Response.Flush();
}
}
catch
{ }
finally
{
HttpContext.Current.Response.Close();
} }

2 下面是使用WriteFile实现下载

/// <summary>
/// 使用WriteFile下载文件
/// </summary>
/// <param name="filePath">相对路径</param>
public void WriteFile(string filePath)
{
try
{
filePath = Server.MapPath(filePath);
if (File.Exists(filePath))
{
FileInfo info = new FileInfo(filePath);
long fileSize = info.Length;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + Server.UrlEncode(info.FullName));
//指定文件大小
HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
HttpContext.Current.Response.WriteFile(filePath, , fileSize);
HttpContext.Current.Response.Flush();
}
}
catch
{ }
finally
{
HttpContext.Current.Response.Close();
}
}

3,下面是分块实现下载

/// <summary>
/// 使用OutputStream.Write分块下载文件
/// </summary>
/// <param name="filePath"></param>
public void WriteFileBlock(string filePath)
{
filePath = Server.MapPath(filePath);
if (!File.Exists(filePath))
{
return;
}
FileInfo info = new FileInfo(filePath);
//指定块大小
long chunkSize = ;
//建立一个4K的缓冲区
byte[] buffer = new byte[chunkSize];
//剩余的字节数
long dataToRead = ;
FileStream stream = null;
try
{
//打开文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); dataToRead = stream.Length; //添加Http头
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + Server.UrlEncode(info.FullName));
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); while (dataToRead > )
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, , Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, , length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
//防止client失去连接
dataToRead = -;
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null)
{
stream.Close();
}
HttpContext.Current.Response.Close();
} }

转:http://www.cnblogs.com/wang7/archive/2012/08/07/2627298.html

C#实现文件下载的更多相关文章

  1. Android 浏览器 —— 使用 WebView 实现文件下载

    对当前的WebView设置下载监听 mCurrentWebView.setDownloadListener(new DownloadListener() { @Override public void ...

  2. C# 文件下载 : WinINet

    在 C# 中,除了 WebClient 我们还可以使用一组 WindowsAPI 来完成下载任务.这就是 Windows Internet,简称 WinINet.本文通过一个 demo 来介绍 Win ...

  3. ASP.net MVC 文件下载的几种方法(欢迎讨论)

    在ASP.net MVC 中有几种下载文件的方法 前提:要下载的文件必须是在服务器目录中的,至于不在web项目server目录中的文件下载我不知道,但是还挺想了解的. 第一种:最简单的超链接方法,&l ...

  4. 让IIS7.0.0.0支持 .iso .7z .torrent .apk等文件下载的设置方法

    IIS默认支持哪些MIME类型呢,我们可以这样查看:打开IIS管理器(计算机--管理--服务和应用程序--Internet信息服务(IIS)管理器:或者Win+R,输入inetmgr,Enter),在 ...

  5. Android中使用AsyncTask实现文件下载以及进度更新提示

    Android提供了一个工具类:AsyncTask,它使创建需要与用户界面交互的长时间运行的任务变得更简单.相对Handler来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和 ...

  6. 利用Tomcat内置的servlet实现文件下载功能

    起因 最近博客所在的VPS挂了又要重装系统,又要重装各种软件. 以前我也经常更换VPS,每次更换都是各种坑爹事情..比如要下载java.下载tomcat.下载mysql..........以前每次我都 ...

  7. 多个文件下载打包生成zip格式下载

    这个多个文件下载生成zip格式必须先引用一个ICSharpCode.SharpZipLib.dll. 代码如下  //将多个文件打包成压缩文件zip格式下载         protected voi ...

  8. .net一般处理程序(httphandler)实现文件下载功能

    Handler文件代码如下: public class MDMExporterWeb : IHttpHandler { public void ProcessRequest(HttpContext c ...

  9. asp.net 文件下载(txt,rar,pdf,word,excel,ppt)

    aspx 文件下载说起来一点都不难,但是在做的过程中还是遇到了一些小小的问题,就是因为这些小小的问题,导致解决起来实在是太难了,其中一个就是Response.End();导致下载文件出现线程终止的情况 ...

  10. JavaScript多文件下载

    对于文件的下载,可以说是一个十分常见的话题,前端的很多项目中都会有这样的需求,比如 highChart 统计图的导出,在线图片编辑中的图片保存,在线代码编辑的代码导出等等.而很多时候,我们只给了一个链 ...

随机推荐

  1. HTML学习之canves元素

    1:绘制画布 和在画布上绘制矩形 <!DOCTYPE html> <html> <head lang="en"> <meta charse ...

  2. OracleHelper 动软生成

    using System; using System.Collections; using System.Collections.Specialized; using System.Data; usi ...

  3. Poj(2407),Greater New York Regional 2015 (D)

    题目链接:http://poj.org/problem?id=2407 Relatives Time Limit: 1000MS   Memory Limit: 65536K Total Submis ...

  4. 利用Spire for .NET实现办公自动化——Spire.Doc

    今天研究了一下E-ICEBLUE公司的Spire for .NET系列产品.我们可以通过利用这个系列的dll库文件轻松的实现办公自动化的需求,而且不需要安装相应的办公软件.有关于Spire .NET系 ...

  5. common-pool2 使用

    common-pool2提供了3中对象池管理方式,它们的使用方式基本一样,这里以GenericObjectPool对象池为例介绍其使用方式,一般实现自己的对象池需要经过2个步骤 1.实现PooledO ...

  6. Java Cryptography Extension (JCE): 放开Java加密算法密钥最大长度16的限制

    1. 在官网下载JCE: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads- ...

  7. Educational Codeforces Round 1 A

    In this problem you are to calculate the sum of all integers from 1 to n, but you should take all po ...

  8. IIS与Apache共用80端口方法[试用成功]

    然后假设apache服务器已经安装完成,打开httpd.conf配置文件,找到这些地方去掉#开启代理模块: LoadModule proxy_module modules/mod_proxy.so L ...

  9. Duilib中系统消息在自己窗口类的使用

    这些Win32消息响应函数,子类只需要重写,不需要在HandleMessage里面再调用一次 开发中遇到的问题,在任务栏关闭程序,会响应WM_SYSCOMMAND消息,因为要给用户提示是否关闭,所以需 ...

  10. uTenux——重新整理底层驱动库

    重新整理底层驱动库 1. 整理chip.h 在chip.h文件中的07----13的宏定义设置位如下,这样我们就不用在工程配中定义sam3s4c这个宏了,为我们以后通用少了一件麻烦事. //#if d ...