[上传下载] 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 ...
随机推荐
- git ignore 的使用
http://www.barretlee.com/blog/2015/09/06/set-gitignore-after-add-file/ 需要注意的 **: 如果一个 pattern 以 ** 开 ...
- Learing WCF Chapter1 Fundamental WCF Concepts
At its core,WCF is a development platform for service-oriented applications. As I mentioned earlier, ...
- bzoj3172
这里学习AC自动机其实对KMP和trie掌握好了之后很容易扩展成AC自动机的这里运用了一个性质由失配指针反向可以建成一棵fail树x串在y串中的出现的次数即为在fail树上以x结尾节点为根的子树中有多 ...
- Flash3D引擎:Away3D 4.1 Alpha版介绍
转自:http://www.cnblogs.com/njflash/archive/2013/01/31/2886912.html Away3D团队和基金会很高兴地宣布首次发布下一个主要的Away3D ...
- 最小生成树之Prim算法,Kruskal算法
Prim算法 1 .概览 普里姆算法(Prim算法),图论中的一种算法,可在加权连通图里搜索最小生成树.意即由此算法搜索到的边子集所构成的树中,不但包括了连通图里的所有顶点(英语:Vertex (gr ...
- [hadoop转载]tearsort
1TB排序通常用于衡量分布式数据处理框架的数据处理能力.Terasort是Hadoop中的的一个排序作业,在2008年,Hadoop在1TB排序基准评估中赢得第一名,耗时209秒.那么Tera ...
- Java 并发包中的读写锁及其实现分析
1. 前言 在Java并发包中常用的锁(如:ReentrantLock),基本上都是排他锁,这些锁在同一时刻只允许一个线程进行访问,而读写锁在同一时 刻可以允许多个读线程访问,但是在写线程访问时,所有 ...
- hdoj 2147 kiki's game【博弈】
kiki's game Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 40000/10000 K (Java/Others)Total ...
- 文件上传工具swfupload[转]
转至:http://zhangqgc.iteye.com/blog/906419 文件上传工具swfupload 示例: 1.JavaScript设置SWFUpload部分(与官方例子类似): var ...
- c语言数据处理!
#include "stdio.h" struct { ]; long nume; ]}; ]; float score; }stur; main() { printf(" ...