C#实现文件下载
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#实现文件下载的更多相关文章
- Android 浏览器 —— 使用 WebView 实现文件下载
对当前的WebView设置下载监听 mCurrentWebView.setDownloadListener(new DownloadListener() { @Override public void ...
- C# 文件下载 : WinINet
在 C# 中,除了 WebClient 我们还可以使用一组 WindowsAPI 来完成下载任务.这就是 Windows Internet,简称 WinINet.本文通过一个 demo 来介绍 Win ...
- ASP.net MVC 文件下载的几种方法(欢迎讨论)
在ASP.net MVC 中有几种下载文件的方法 前提:要下载的文件必须是在服务器目录中的,至于不在web项目server目录中的文件下载我不知道,但是还挺想了解的. 第一种:最简单的超链接方法,&l ...
- 让IIS7.0.0.0支持 .iso .7z .torrent .apk等文件下载的设置方法
IIS默认支持哪些MIME类型呢,我们可以这样查看:打开IIS管理器(计算机--管理--服务和应用程序--Internet信息服务(IIS)管理器:或者Win+R,输入inetmgr,Enter),在 ...
- Android中使用AsyncTask实现文件下载以及进度更新提示
Android提供了一个工具类:AsyncTask,它使创建需要与用户界面交互的长时间运行的任务变得更简单.相对Handler来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和 ...
- 利用Tomcat内置的servlet实现文件下载功能
起因 最近博客所在的VPS挂了又要重装系统,又要重装各种软件. 以前我也经常更换VPS,每次更换都是各种坑爹事情..比如要下载java.下载tomcat.下载mysql..........以前每次我都 ...
- 多个文件下载打包生成zip格式下载
这个多个文件下载生成zip格式必须先引用一个ICSharpCode.SharpZipLib.dll. 代码如下 //将多个文件打包成压缩文件zip格式下载 protected voi ...
- .net一般处理程序(httphandler)实现文件下载功能
Handler文件代码如下: public class MDMExporterWeb : IHttpHandler { public void ProcessRequest(HttpContext c ...
- asp.net 文件下载(txt,rar,pdf,word,excel,ppt)
aspx 文件下载说起来一点都不难,但是在做的过程中还是遇到了一些小小的问题,就是因为这些小小的问题,导致解决起来实在是太难了,其中一个就是Response.End();导致下载文件出现线程终止的情况 ...
- JavaScript多文件下载
对于文件的下载,可以说是一个十分常见的话题,前端的很多项目中都会有这样的需求,比如 highChart 统计图的导出,在线图片编辑中的图片保存,在线代码编辑的代码导出等等.而很多时候,我们只给了一个链 ...
随机推荐
- Financial Management 分类: POJ 2015-06-11 10:51 12人阅读 评论(0) 收藏
Financial Management Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 164431 Accepted: ...
- 【20160924】GOCVHelper MFC增强算法(3)
//获得当前目录路径 static CString GetLocalPath(){ CString csCfgFilePath; GetModuleFi ...
- 使用selenium来完成的例子
地址:http://www.tuicool.com/articles/rimeey
- 自己模拟实现spring IOC原理
1.1.IoC是什么 Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对 ...
- 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神
原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...
- 模块mod_h323的编译
去h.323plus官网上下载关联的库 http://www.h323plus.org/source/ 很贴心,分操作系统下载,而且关联的ptlib库的版本也一并列了出来. 一.编译ptlib库 ex ...
- Java——Socket编程(一)
1. 网络基础知识 两台机器之间需要进行通信,需要满足的条件: 每个机器有一个唯一的标识符(IP地址): 他们之间进行通信需要用同一种语言(协议): 每台主机上面有多个应用程序,如QQ,微博,迅雷等, ...
- PowerShell 4 on win7 sp1
https://www.microsoft.com/en-hk/download/details.aspx?id=40855 文件太多了,按照这个http://stackoverflow.com/qu ...
- @SuppressWarnings—注解用法详解
一.前言 编码时我们总会发现如下变量未被使用的警告提示: 上述代码编译通过且可以运行,但每行前面的“感叹号”就严重阻碍了我们判断该行是否设置的断点了.这时我们可以在方法前添加 @SuppressWar ...
- CentOS 6.5 64位 安装zabbix-2.2.0
安装环境: VM 10 + CentOS-6.5-x86_64-minimal 虚拟机网络是NAT方式, 动态IP Xshell登录到Centos操作 刚装的centos,啥都没有,先配一下yum 首 ...