据我所知道的.. asp.net 上传大文件需要以下几步:1 . HTML 页面<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
<INPUT type="file">
<INPUT type="submit" value="Button">
</form>2. 修改webconfi.conf 中的<httpMoudles> 标记. 让它指向自定义IHttpMolude 接口.3. 实现 httpRequest_begin (obect sender, EventArgse) 事件我也是从人家那里看来的, 基本过程如下:void httpRequest_begin (obect sender, EventArgse)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
HttpWorkerRequest request1 = (HttpWorkerRequest) ((IServiceProvider)ttpContext.Current).GetService(typeof(HttpWorkerRequest)); if (context.Request.ContentType.IndexOf("multipart/form-data")>-1) //仅处理multipart/form-data数据
{
FileStream fs=new FileStream("d:\\test1.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
context.Response.Write(request1.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
// 按其它人说法是可以返回上传文件大小..我测试结果却是不论什么文件都返回194,196两个数值.
buf1=request1.GetPreloadedEntityBody();
if(!request1.IsEntireEntityBodyIsPreloaded())
// 上句 这里的request1.IsEntireEntityBodyIsPreloaded()永远反回false .. 好忧闷. {
while (request1.IsClientConnected())
{ buf2=new byte[290];
readByte=request1.ReadEntityBody(buf2,290);
context.Response.Write(readByte.ToString()+"***");
context.Response.End();
fs.Write(buf2,0,buf2.Length);
}
fs.Close();
}
}
}-------------上面是个大概示意代码.. 出问题部分已经写出来了. 我也是看着人家源码来弄的.. 结果就是出来...有高手能指点吗?
<INPUT type="file">
<INPUT type="submit" value="Button">
</form>2. 修改webconfi.conf 中的<httpMoudles> 标记. 让它指向自定义IHttpMolude 接口.3. 实现 httpRequest_begin (obect sender, EventArgse) 事件我也是从人家那里看来的, 基本过程如下:void httpRequest_begin (obect sender, EventArgse)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
HttpWorkerRequest request1 = (HttpWorkerRequest) ((IServiceProvider)ttpContext.Current).GetService(typeof(HttpWorkerRequest)); if (context.Request.ContentType.IndexOf("multipart/form-data")>-1) //仅处理multipart/form-data数据
{
FileStream fs=new FileStream("d:\\test1.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
context.Response.Write(request1.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
// 按其它人说法是可以返回上传文件大小..我测试结果却是不论什么文件都返回194,196两个数值.
buf1=request1.GetPreloadedEntityBody();
if(!request1.IsEntireEntityBodyIsPreloaded())
// 上句 这里的request1.IsEntireEntityBodyIsPreloaded()永远反回false .. 好忧闷. {
while (request1.IsClientConnected())
{ buf2=new byte[290];
readByte=request1.ReadEntityBody(buf2,290);
context.Response.Write(readByte.ToString()+"***");
context.Response.End();
fs.Write(buf2,0,buf2.Length);
}
fs.Close();
}
}
}-------------上面是个大概示意代码.. 出问题部分已经写出来了. 我也是看着人家源码来弄的.. 结果就是出来...有高手能指点吗?
public class HttpUploadModule: IHttpModule
{
public HttpUploadModule()
{
} public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(this.Application_BeginRequest);
application.EndRequest += new EventHandler(this.Application_EndRequest);
application.Error += new EventHandler(this.Application_Error);
} public void Dispose()
{
} private void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
HttpWorkerRequest request = GetWorkerRequest(app.Context);
Encoding encoding = app.Context.Request.ContentEncoding; int bytesRead = 0; // 已读数据大小
int read; // 当前读取的块的大小
int count = 8192; // 分块大小
byte[] buffer; // 保存所有上传的数据
string uploadId; // 唯一标志当前上传的ID
Progress progress; // 记录当前上传的进度信息 if (request != null)
{
// 返回 HTTP 请求正文已被读取的部分。
//
byte[] tempBuff = request.GetPreloadedEntityBody();
// 如果是附件上传
//
if (
tempBuff != null
&& IsUploadRequest(app.Request)
)
{
// 获取上传大小
//
long length = long.Parse(request.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));
// 当前上传的ID,用来唯一标志当前的上传
// 用此UploadID,可以通过其他页面获取当前上传的进度
//
uploadId = app.Context.Request.QueryString["UploadID"];
// 开始记录当前上传状态
//
progress = new Progress(length, uploadId);
progress.SetState(UploadState.ReceivingData);
buffer = new byte[length];
count = tempBuff.Length; // 分块大小 // 将已上传数据复制过去
//
Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, count); // 开始记录已上传大小
//
bytesRead = tempBuff.Length;
progress.SetBytesRead(bytesRead);
SetProgress(uploadId, progress, app.Application); // 循环分块读取,直到所有数据读取结束
//
while (request.IsClientConnected() &&
!request.IsEntireEntityBodyIsPreloaded() &&
bytesRead < length
)
{
// 如果最后一块大小小于分块大小,则重新分块
//
if (bytesRead + count > length)
{
count = (int)(length - bytesRead);
tempBuff = new byte[count];
} // 分块读取
//
read = request.ReadEntityBody(tempBuff, count);
// 复制已读数据块
//
Buffer.BlockCopy(tempBuff, 0, buffer, bytesRead, read);
// 记录已上传大小
//
bytesRead += read;
progress.SetBytesRead(bytesRead);
SetProgress(uploadId, progress, app.Application); }
if (
request.IsClientConnected() &&
!request.IsEntireEntityBodyIsPreloaded()
)
{
// 传入已上传完的数据
//
InjectTextParts(request, buffer); // 表示上传已结束
//
progress.SetBytesRead(bytesRead);
progress.SetState(UploadState.Complete);
SetProgress(uploadId, progress, app.Application); }
}
}
} /// <summary>
/// 结束请求后移除进度信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Application_EndRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication; if (IsUploadRequest(app.Request))
{
SetUploadState(app, UploadState.Complete);
RemoveFrom(app);
} } /// <summary>
/// 如果出错了设置进度信息中状态为“Error”
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Application_Error(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication; if (IsUploadRequest(app.Request))
{
SetUploadState(app, UploadState.Error);
} } /// <summary>
/// 设置当前上传进度信息的状态
/// </summary>
/// <param name="app"></param>
/// <param name="state"></param>
void SetUploadState(HttpApplication app, UploadState state)
{
string uploadId = app.Request.QueryString["UploadID"];
if (uploadId != null && uploadId.Length > 0)
{
Progress progress = GetProgress(uploadId, app.Application);
if (progress != null)
{
progress.SetState(state);
SetProgress(uploadId, progress, app.Application);
}
}
} /// <summary>
/// 设置当前上传的进度信息
/// 根据UploadID记录在Application中
/// </summary>
/// <param name="uploadId"></param>
/// <param name="progress"></param>
/// <param name="application"></param>
void SetProgress(string uploadId, Progress progress, HttpApplicationState application)
{
if (uploadId == null || uploadId == string.Empty || progress == null)
return;
application.Lock();
application["OpenlabUpload_" + uploadId] = progress;
application.UnLock();
} /// <summary>
/// 从Application中移出进度信息
/// </summary>
/// <param name="app"></param>
void RemoveFrom(HttpApplication app)
{
string uploadId = app.Request.QueryString["UploadID"];
HttpApplicationState application = app.Application;
if (uploadId != null && uploadId.Length > 0)
{
application.Remove("OpenlabUpload_" + uploadId);
}
} /// <summary>
/// 根据UploadID获取上传进度信息
/// </summary>
/// <param name="uploadId"></param>
/// <param name="application"></param>
/// <returns></returns>
public static Progress GetProgress(string uploadId, HttpApplicationState application)
{
Progress progress = application["OpenlabUpload_" + uploadId] as Progress;
return progress;
} HttpWorkerRequest GetWorkerRequest(HttpContext context)
{ IServiceProvider provider = (IServiceProvider)HttpContext.Current;
return (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
} /// <summary>
/// 传入已上传完的数据
/// </summary>
/// <param name="request"></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);
}
} private static bool StringStartsWithAnotherIgnoreCase(string s1, string s2)
{
return (string.Compare(s1, 0, s2, 0, s2.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");
}
}
}
自己尝试下面的写法,很简单的.//页面HTML代码
<form id="Form1" method="post" runat="server">
<INPUT type="file" runat=server id=file1>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>/// <summary>
/// 上传图片(后台代码)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button1_Click(object sender, System.EventArgs e)
{
System.Web.HttpPostedFile myPost = this.Request.Files[0];
//判断文件大小
if(myPost.ContentLength !=0)
{
//指定存盘路径
string uploadpath = this.Server.MapPath("uploadfile");
//取得上传文件全路径名
string tmpfilename = myPost.FileName;
//文件名
string filename = tmpfilename.Substring(tmpfilename.LastIndexOf("\\") + 1); //获取要保存的路径
string fileSavePath = uploadpath + "\\" + filename; //保存原图片
myPost.SaveAs(fileSavePath);
}
}
HttpWorkerRequest.IsEntireEntityBodyIsPreloaded()
HttpWorkerRequest.ReadEntityBody:从客户端读取当前的请求中的数据验证了!IsEntireEntityBodyIsPreloaded之后就可以ReadEntityBody了。这个对象MSDN文档上描述的很少,所以这只是我对它的一点理解,也许不准确,仅供参考。
http://www.cnblogs.com/bestcomy/archive/2004/06/09/14267.html