[上传下载] C#FileDown文件下载类 (转载)
主要功能如下
.参数为虚拟路径
.获取物理地址
.普通下载
.分块下载
.输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
看下面代码吧
/// <summary>
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:[url=http://www.sufeinet.com/thread-655-1-1.html]http://www.sufeinet.com/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.IO;
using System.Threading;
using System.Web; namespace DotNet.Utilities
{
/// <summary>
/// 文件下载类
/// </summary>
public class FileDown
{
public FileDown()
{ } /// <summary>
/// 参数为虚拟路径
/// </summary>
public static string FileNameExtension(string FileName)
{
return Path.GetExtension(MapPathFile(FileName));
} /// <summary>
/// 获取物理地址
/// </summary>
public static string MapPathFile(string FileName)
{
return HttpContext.Current.Server.MapPath(FileName);
} /// <summary>
/// 普通下载
/// </summary>
/// <param name="FileName">文件虚拟路径</param>
public static void DownLoadold(string FileName)
{
string destFileName = MapPathFile(FileName);
if (File.Exists(destFileName))
{
FileInfo fi = new FileInfo(destFileName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(destFileName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
} /// <summary>
/// 分块下载
/// </summary>
/// <param name="FileName">文件虚拟路径</param>
public static void DownLoad(string FileName)
{
string filePath = MapPathFile(FileName);
long chunkSize = ; //指定块大小
byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
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=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
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
{
dataToRead = -; //防止client失去连接
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null) stream.Close();
HttpContext.Current.Response.Close();
}
} /// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="_Request">;Page.Request对象</param>
/// <param name="_Response">;Page.Response对象</param>
/// <param name="_fileName">下载文件名</param>
/// <param name="_fullPath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
//---------------------------------------------------------------------
//调用:
// string FullPath=Server.MapPath("count.txt");
// ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
//---------------------------------------------------------------------
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false; long fileLength = myFile.Length;
long startBytes = ;
int pack = ; //10K bytes
int sleep = (int)Math.Floor((double)( * pack / _speed)) + ; if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = ;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != )
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - , fileLength));
} _Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + ; for (int i = ; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
}
}
[上传下载] C#FileDown文件下载类 (转载)的更多相关文章
- java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)
1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...
- JAVAWEB之文件的上传下载
文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...
- 转载:JavaWeb 文件上传下载
转自:https://www.cnblogs.com/aaron911/p/7797877.html 1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端 ...
- 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)
前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...
- ftp上传下载工具类
package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...
- [转载]如何通过ssh进行上传/下载
[转载]如何通过ssh进行上传/下载 学校给配了服务器的用户账号,但是怎么向服务器中上传以及下载文件呢?Windows下可以使用Xftp和Xshell,但是Linux下能不能用命令行解决呢? 什么是S ...
- (转载)基于Bash命令行的百度云上传下载工具
原文链接:http://hi.baidu.com/meoow/item/aef5814bbd5be3e1bcf451e9 这是我根据百度云PCS的API写的一个基于bash的命令行工具, 使用了cur ...
- FastDFS上传/下载过程[转载-经典图列]
FastDFS上传/下载过程: 首先客户端 client 发起对 FastDFS 的文件传输动作,是通过连接到某一台 Tracker Server 的指定端口来实现的,Tracker Server 根 ...
- SpringMVC文件上传下载
在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...
随机推荐
- WCF - net.pipe vs. net.tcp vs. http Bindings
WCF - net.pipe vs. net.tcp vs. http Bindings 问题: I'm new to WCF and would like to know the differenc ...
- C++ Prime:const的引用
可以把引用绑定到const对象上,就像绑定到其他对象上一样,我们称之为对常量的引用.与普通引用不同的是,对常量的引用不能被用作修改它所绑定的对象: ; const int &r1 = ci; ...
- oracle查询转换_view merge
oracle对于子查询的支持做的很好,oracle optimizer会对inline view进行query transfomation,即视图合并,不过也经常带来意想不到的问题.下面是一个inli ...
- BZOJ_4196_[NOI2015]_软件包管理器_(树链剖分)
描述 http://www.lydsy.com/JudgeOnline/problem.php?id=4196 给出一棵树,树上点权为0或1.u权值为1的条件是从根节点到u路径上的所有点权值都为1.u ...
- POJ_2100_Graveyard_Design_(尺取法)
描述 http://poj.org/problem?id=2100 求连续平方和=n的序列个数,并输出序列. Graveyard Design Time Limit: 10000MS Memory ...
- 实验记录贴 —— 账号同步实验 RTX 和 LDAP(AD域)
目前,公司有多个系统,RTX,邮箱(MD),OA,NC. 这些系统之间,如果要实现单点登录的话,账户肯定需要同步,或者某一种映射机制. 如果所有数据都和中央账号数据库(LDAP,这里是AD域)看齐,那 ...
- asp.net获取当前页面文件名,参数,域名等方法。统一session验证和权限验证的方法
转:http://blog.csdn.net/llll29550242/article/details/6054323 ASP.net后台获取当前页面的文件名 System.IO.Path.GetFi ...
- Java多线程内存模型
Java虚拟机规范中试图定义一种Java内存模型(Java Memory Model,JMM)来屏蔽掉各种硬件和操作系统的内存访问差异,以实现让Java程序在各种平台下都能达到一致的并发效果.在此之前 ...
- useradd、passwd、userdel
useradd是新建用户 userdel -r 是删除用户 passwd是修改密码 groupadd是新建组 groupdel是删除组 useradd yonghu 为添加用户 echo " ...
- PHP中使用函数array_merge()合并数组
如果明白数组其实就是map的话,我想你就会明白array_merge为什么要这么实现了 PHP中合并数组分成两种情况 1.如果这两个数组中有相同的字符串键名: <?php header('Con ...