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. Maya Calendar 分类: POJ 2015-06-11 21:44 12人阅读 评论(0) 收藏

    Maya Calendar Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 70016   Accepted: 21547 D ...

  2. SharePoint自动化系列——Add content type to list.

    转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/ 将创建好的content type(若是跨web application需要事先publish c ...

  3. shell控制流结构笔记

      man  test 可以看见这些     比较符号:-lt小于 -le小于等于   -gt大于   -ge大于等于  -ne不等于   -eq等于              < 小于(需要双 ...

  4. Scala循环操作

    val buf = new scala.collection.mutable.ArrayBuffer[Int] for (i <- 0 to 10) { buf += i } buf += 11 ...

  5. 【MySQL】MySQL的Sequence

    Oracle的Sequence用爽了,发现MySQL没有Sequence,那么,自己写一个呗. > 最简单的实现 先建一个表存储当前值: CREATE TABLE `t_sequence` ( ...

  6. 十一、Swing

    1.Swing常用窗体 (1)JFrame框架窗体 JFrame窗体是一个容器,是Swing程序中各组件的载体. 语法:JFrame jf = new JFrame(title); Container ...

  7. iOS深入学习(再谈block)

    之前写过一篇博客,把Block跟delegate类比,说明了使用block,可以通过更少的代码实现代理的功能.那篇博客将block定义为类的property. 过了这么长时间,对于block的内容有了 ...

  8. XML文件解析DOM解析和SAX解析

    解析一个XML文档有哪些内容解析有:dom和sax两种dom:把整个XML文档放入内存,适合XML随机访问,占用内存资源大sax:事件驱动型的XML解析方式,顺序读取,不用一次装载整个文件,遇到标签会 ...

  9. CodeForces 478C Table Decorations

    Table Decorations Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u ...

  10. HDU 4870 Rating 概率DP

    Rating Time Limit:5000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Statu ...