会员
周边
众包
新闻
博问
闪存
赞助商
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
加勒比海盗
人生最大的幸事,得一贤妻,得一知己也。
博客园
首页
新随笔
联系
订阅
管理
文件下载
文件下载
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Threading;
namespace Common
{
public class FileUtil
{
# region 获取文件信息
/// <summary>
/// 获取文件信息
/// </summary>
/// <returns></returns>
public static string GetFileInfo(Stream objStream)
{
//UTF-8
StreamReader sr = new StreamReader(objStream, System.Text.Encoding.GetEncoding("GB2312"));
string strFileContent = sr.ReadToEnd();
sr.Close();
return strFileContent;
}
# endregion
# region Http 文件下载
// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
// 输入参数 _Request: Page.Request对象, _Response: Page.Response对象, _fileName: 下载文件名, sr: 文件流, _speed 每秒允许下载的字节数
// 返回是否成功
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, Stream sr, long _speed)
{
try
{
Stream myFile = sr;
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
double pack = 10240; //10K bytes
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
//Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, 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((fileLength - startBytes) / pack) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
# endregion
}
}
posted @
2012-05-06 00:07
加勒比海盗V
阅读(
205
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告