如using System;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web;
//实现IHttpModule接口
public class HttpUploadModule : IHttpModule
{
///<summary>
///默认无参构造函数
///</summary>
public HttpUploadModule()
{
}
///<summary>
///初始化,在此添加事件的响应
///</summary>
///<param name="application">Web应用程序对像</param>
public void Init(HttpApplication application)
{
//订阅响应HTTP请求事件
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
}
///<summary>
///释放使用的资源
///</summary>
public void Dispose()
{
//
//TODO:如果需要手工为类做一些清除工作,在此添加代码
//
}
///<summary>
///开始一个HTTP请求事件的处理
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication; //获得Web应用程序对像 string uploadKey = string.Empty;
//-----------下面这一句是我来取当前Upload的一个guid标示的,但用了这一段下面的 read就一直为0
if (app.Context.Request.Form["txtGuidTime"] != null)
{
uploadKey = app.Context.Request.Form["txtGuidTime"];
}
//---------------如果这里直接写为 uploadKey = "123456";程序就不会错 HttpWorkerRequest request = GetWorkerRequest(app.Context); //获得Http请求对像
Encoding encoding = app.Context.Request.ContentEncoding; //得到请求文本的编码类型
int bytesRead = 0; //已读数据大小
int read; //当前读取的块的大小
int count = 8192; //分块大小
byte[] buffer; //保存所有上传的数据 if (request != null) //如果请求不为空
{
//返回 HTTP 请求正文已被读取的部分。
byte[] tempBuff = request.GetPreloadedEntityBody(); //如果是附件上传
if (tempBuff != null && IsUploadRequest(app.Request))
{
UploadFileInfo info = new UploadFileInfo();
info.Message = "文件正在上传,请稍候...";
System.Threading.Thread.Sleep(1000);
//获取上传大小
long length = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)); info.FileSzie = length; buffer = new byte[length]; //定义相应大小的缓存区
count = tempBuff.Length; //分块大小 //将已上传数据复制过去
Buffer.BlockCopy(tempBuff, //源数据
0, //从0开始读
buffer, //目标容器
bytesRead, //指定存储的开始位置
count); //要复制的字节数。 //开始记录已上传大小
bytesRead = tempBuff.Length; info.UploadSize = bytesRead;
info.UploadPercent = Convert.ToInt32((info.UploadSize / info.FileSzie) * 100);
System.Web.HttpRuntime.Cache.Insert(uploadKey, info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20)); //循环分块读取,直到所有数据读取结束
while (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded() && bytesRead < length)
{
System.Threading.Thread.Sleep(10);
//如果最后一块大小小于分块大小,则重新分块
if (bytesRead + count > length)
{
count = (int)(length - bytesRead);
tempBuff = new byte[count];
}
//分块读取
read = request.ReadEntityBody(tempBuff, count);
//-------------------
//就是这里,如果我上面取了form的值的话这里的read就一直为0,然后程序就在这里死循环了
//-------------------
//复制已读数据块
Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, read);
//记录已上传大小
bytesRead += read; info.UploadSize = bytesRead;
info.UploadPercent = Convert.ToInt32((info.UploadSize / info.FileSzie) * 100);
if (info.UploadPercent == 100)
{
info.Message = "文件上传成功,服务器正在保存文件!";
}
System.Web.HttpRuntime.Cache.Insert(uploadKey, info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20));
}
if (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded())
{
//传入已上传完的数据
InjectTextParts(request, buffer);
}
}
}
} ///<summary>
///获得Http请求对像
///</summary>
///<param name="context">Http请求内容</param>
///<returns>Http请求对像</returns>
HttpWorkerRequest GetWorkerRequest(HttpContext context)
{
IServiceProvider provider = (IServiceProvider)HttpContext.Current;
return (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
} ///<summary>
///传入已上传完的数据
///</summary>
///<param name="request">Http请求对像</param>
///<param name="textParts"></param>
void InjectTextParts(HttpWorkerRequest request, byte[] textParts)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = request.GetType(); //获得请求的类型 while ((type != null) && (type.FullName != "System.Web.Hosting.ISAPIWorkerRequest"))
{
type = type.BaseType;
} if (type != null)
{
type.GetField("_contentAvailLength", bindingFlags).SetValue(request, textParts.Length);
type.GetField("_contentTotalLength", bindingFlags).SetValue(request, textParts.Length);
type.GetField("_preloadedContent", bindingFlags).SetValue(request, textParts);
type.GetField("_preloadedContentRead", bindingFlags).SetValue(request, true);
}
}
/// <summary>
/// 比较两个字符串指定位置的指定长度是否相等
/// 忽略大小写及区域不同
/// </summary>
/// <param name="s1">要比较的第一个字符串</param>
/// <param name="s2">要比较的第二个字符串</param>
/// <returns>
/// 小于零 str1 中的子字符串小于 str2 中的子字符串。
/// 等于零 子字符串相等,或者 length 为零。
/// 大于零 str1 中的子字符串大于 str2 中的子字符串。
/// </returns>
private static bool StringStartsWithAnotherIgnoreCase(string str1, string str2)
{
return (string.Compare(str1, 0, str2, 0, str2.Length, true, CultureInfo.InvariantCulture) == 0);
} ///<summary>
///是否为附件上传
///判断的根据是ContentType中有无multipart/form-data
///</summary>
///<param name="request"></param>
///<returns></returns>
bool IsUploadRequest(HttpRequest request)
{
return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
}
}
谢谢
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web;
//实现IHttpModule接口
public class HttpUploadModule : IHttpModule
{
///<summary>
///默认无参构造函数
///</summary>
public HttpUploadModule()
{
}
///<summary>
///初始化,在此添加事件的响应
///</summary>
///<param name="application">Web应用程序对像</param>
public void Init(HttpApplication application)
{
//订阅响应HTTP请求事件
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
}
///<summary>
///释放使用的资源
///</summary>
public void Dispose()
{
//
//TODO:如果需要手工为类做一些清除工作,在此添加代码
//
}
///<summary>
///开始一个HTTP请求事件的处理
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication; //获得Web应用程序对像 string uploadKey = string.Empty;
//-----------下面这一句是我来取当前Upload的一个guid标示的,但用了这一段下面的 read就一直为0
if (app.Context.Request.Form["txtGuidTime"] != null)
{
uploadKey = app.Context.Request.Form["txtGuidTime"];
}
//---------------如果这里直接写为 uploadKey = "123456";程序就不会错 HttpWorkerRequest request = GetWorkerRequest(app.Context); //获得Http请求对像
Encoding encoding = app.Context.Request.ContentEncoding; //得到请求文本的编码类型
int bytesRead = 0; //已读数据大小
int read; //当前读取的块的大小
int count = 8192; //分块大小
byte[] buffer; //保存所有上传的数据 if (request != null) //如果请求不为空
{
//返回 HTTP 请求正文已被读取的部分。
byte[] tempBuff = request.GetPreloadedEntityBody(); //如果是附件上传
if (tempBuff != null && IsUploadRequest(app.Request))
{
UploadFileInfo info = new UploadFileInfo();
info.Message = "文件正在上传,请稍候...";
System.Threading.Thread.Sleep(1000);
//获取上传大小
long length = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)); info.FileSzie = length; buffer = new byte[length]; //定义相应大小的缓存区
count = tempBuff.Length; //分块大小 //将已上传数据复制过去
Buffer.BlockCopy(tempBuff, //源数据
0, //从0开始读
buffer, //目标容器
bytesRead, //指定存储的开始位置
count); //要复制的字节数。 //开始记录已上传大小
bytesRead = tempBuff.Length; info.UploadSize = bytesRead;
info.UploadPercent = Convert.ToInt32((info.UploadSize / info.FileSzie) * 100);
System.Web.HttpRuntime.Cache.Insert(uploadKey, info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20)); //循环分块读取,直到所有数据读取结束
while (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded() && bytesRead < length)
{
System.Threading.Thread.Sleep(10);
//如果最后一块大小小于分块大小,则重新分块
if (bytesRead + count > length)
{
count = (int)(length - bytesRead);
tempBuff = new byte[count];
}
//分块读取
read = request.ReadEntityBody(tempBuff, count);
//-------------------
//就是这里,如果我上面取了form的值的话这里的read就一直为0,然后程序就在这里死循环了
//-------------------
//复制已读数据块
Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, read);
//记录已上传大小
bytesRead += read; info.UploadSize = bytesRead;
info.UploadPercent = Convert.ToInt32((info.UploadSize / info.FileSzie) * 100);
if (info.UploadPercent == 100)
{
info.Message = "文件上传成功,服务器正在保存文件!";
}
System.Web.HttpRuntime.Cache.Insert(uploadKey, info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(20));
}
if (request.IsClientConnected() && !request.IsEntireEntityBodyIsPreloaded())
{
//传入已上传完的数据
InjectTextParts(request, buffer);
}
}
}
} ///<summary>
///获得Http请求对像
///</summary>
///<param name="context">Http请求内容</param>
///<returns>Http请求对像</returns>
HttpWorkerRequest GetWorkerRequest(HttpContext context)
{
IServiceProvider provider = (IServiceProvider)HttpContext.Current;
return (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
} ///<summary>
///传入已上传完的数据
///</summary>
///<param name="request">Http请求对像</param>
///<param name="textParts"></param>
void InjectTextParts(HttpWorkerRequest request, byte[] textParts)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; Type type = request.GetType(); //获得请求的类型 while ((type != null) && (type.FullName != "System.Web.Hosting.ISAPIWorkerRequest"))
{
type = type.BaseType;
} if (type != null)
{
type.GetField("_contentAvailLength", bindingFlags).SetValue(request, textParts.Length);
type.GetField("_contentTotalLength", bindingFlags).SetValue(request, textParts.Length);
type.GetField("_preloadedContent", bindingFlags).SetValue(request, textParts);
type.GetField("_preloadedContentRead", bindingFlags).SetValue(request, true);
}
}
/// <summary>
/// 比较两个字符串指定位置的指定长度是否相等
/// 忽略大小写及区域不同
/// </summary>
/// <param name="s1">要比较的第一个字符串</param>
/// <param name="s2">要比较的第二个字符串</param>
/// <returns>
/// 小于零 str1 中的子字符串小于 str2 中的子字符串。
/// 等于零 子字符串相等,或者 length 为零。
/// 大于零 str1 中的子字符串大于 str2 中的子字符串。
/// </returns>
private static bool StringStartsWithAnotherIgnoreCase(string str1, string str2)
{
return (string.Compare(str1, 0, str2, 0, str2.Length, true, CultureInfo.InvariantCulture) == 0);
} ///<summary>
///是否为附件上传
///判断的根据是ContentType中有无multipart/form-data
///</summary>
///<param name="request"></param>
///<returns></returns>
bool IsUploadRequest(HttpRequest request)
{
return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
}
}
谢谢
解决方案 »
- 在C#中如何处理一异常,急!!!
- 请教一个asp.net 论坛禁言功能
- 碰到这样的面试题你能给出像样的答案吗?
- [求教]asp.net中的javascript验证问题
- system.guid怎么转成字符型.?????????
- 如何通过ADO.NET 获取Excel工作表的名称(急,在线等)
- 请问如何获得DropListDown控件的已选中项的DataTextField值啊
- 问各位朋友一个datatable的动态列宽度问题,知道的朋友请帮帮忙
- asp.net 启动一个进程,调用一个exe程序,为什么这个exe进程在任务管理器中看得到,但CPU时间始终为零,界面也不出来,如果启动的exe程序
- 菜鸟求教!!!水晶报表问题,在线等!!!
- 弹出窗口浏览器如何不提示阻止
- 如何得到跳转后的URL?
if (app.Context.Request.Form["txtGuidTime"] != null)
{
uploadKey = "1234";//app.Context.Request.Form["txtGuidTime"];
}
这样都不行
访问了Request.Form
后面的read就为0了
能否在你操作之前用一个Request对象装载一下当前的Request
下面那样试试,看这样丢不丢private void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication; //获得Web应用程序对像System.Web.HttpRequest req= app.Context.Request;
string uploadKey = string.Empty; if (req.Form["txtGuidTime"] != null)
{
uploadKey = req.Form["txtGuidTime"];
}
....