handler 类为: namespace CoolUpload { public class module : IHttpModule { private string path = @"d:\iis\"; public void Dispose() { } public void Init(HttpApplication application) { application.BeginRequest += (new EventHandler(this.BeginRequest)); } public void BeginRequest(Object sender, EventArgs e) { HttpApplication context = sender as HttpApplication; if (context.Request.ContentType.ToLower().StartsWith("multipart/form-data")) { IServiceProvider provider = (IServiceProvider)HttpContext.Current; HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest)); if (!wr.HasEntityBody()) return; int theOtherLength = 0; int contentLength; string contentType; contentLength = Convert.ToInt32(wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)); contentType = wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType); FileStream fs = null; ... ... 写文件 .... //处理第一次读取的内容 byte[] b1 = wr.GetPreloadedEntityBody(); fs.Write(b1, 0, b1.Length); theOtherLength = contentLength - b1.Length; b1 = null; int n = 65536; int i = 0; //读取剩余的数据,接着写文件 while (theOtherLength > 0) { byte[] b = new byte[n]; int readbytes; if (theOtherLength <= n) { readbytes = wr.ReadEntityBody(b, theOtherLength); } else { readbytes = wr.ReadEntityBody(b, n); } fs.Write(b, 0, readbytes); b = null; theOtherLength -= readbytes; i++; } fs.Close(); fs = null; } } } } ---------------------- 断点续传 Stream fileStream = null; try { fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read); //以流的方式打开文件 file_size = fileStream.Length; fileStream.Position = pos ; //设置断点续传的起点 DateTime lastTime = DateTime.Now ; while(file_size > 0) { if(Response.IsClientConnected) { i++; real_length = fileStream.Read(buffer, 0, 2048); //将数据读入缓冲区 Response.OutputStream.Write(buffer, 0, real_length); //将缓冲区中的数据输出 Response.Flush(); //立即输出 file_size -= real_length; buffer = new Byte[2048]; } else { file_size = -1; } } } catch(Exception ex) { Response.Write("下载文件时发生错误:" + ex.Message); } finally { if(fileStream != null) fileStream.Close(); } |
|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )
GMT+8, 2024-9-30 13:25 , Processed in 0.125530 second(s), 12 queries , Gzip On, MemCache On.
Powered by Discuz! X3.5
© 2001-2023 Discuz! Team.