异步文件下载(随写)

我起初是想实现大文件可继传异步下载,第一个版本异步,继传还没实现后继待续.
以下用了两种实现方法,注释部分是另一种实现方法
主要实现类
using System;
using System.Data;
using System.Web;
using System.Threading;
using System.IO;
using System.Collections;
using Spider.Model.XML;

namespace Spider.Model.AsyncNoCacheDown
{
   

    
class AsynchOperation : IAsyncResult
    
{
        
private bool _completed;
        
private Object _state;
        
private AsyncCallback _callback;
        
private HttpContext _context;

        
bool IAsyncResult.IsCompleted get return _completed; } }
        WaitHandle IAsyncResult.AsyncWaitHandle 
get return null; } }
        Object IAsyncResult.AsyncState 
get return _state; } }
        
bool IAsyncResult.CompletedSynchronously get return false; } }

        
static Hashtable mimeMap = null;

        
public AsynchOperation(AsyncCallback callback, HttpContext context, Object state)
        
{
            _callback 
= callback;
            _context 
= context;
            _state 
= state;
            _completed 
= false;

            XMLHelper XmlHelper 
= new XMLHelper();
            mimeMap 
= XmlHelper.GetDataToHashtable(_context.Server.MapPath(@"/AsyncNoCacheDown/ModelConfig/MIMETypeTable.xml"), "MIMEITEM");
        }


        
public void StartAsyncWork()
        
{
            ThreadPool.QueueUserWorkItem(
new WaitCallback(StartAsyncTask), null);
        }


        
private void StartAsyncTask(Object workItemState)
        
{
            _context.Response.Write(
"<p>Completion IsThreadPoolThread is " + Thread.CurrentThread.IsThreadPoolThread + "</p>\r\n");

            _context.Response.Write(
"Hello World from Async Handler!");

           

            
string fileName = _context.Request.Params["DownFileName"];
            
string filePath = "DownFiles/";

             _context.Response.Write(fileName);

            
string path = _context.Server.MapPath(filePath+fileName);

            System.IO.FileInfo  toDownload 
= new System.IO.FileInfo(path);


            
if (toDownload.Exists)
            
{
                
/*  块读取
                long DownFileBufferSize = 1000; // Read file buffer size.
                byte[] buffer = new byte[DownFileBufferSize]; // Read file buffer.
                long oldReaded = 0; // File already  read size. 
                
*/


                _context.Response.Clear();
                _context.Response.Charset 
= "UTF8";
                
try
                
{
                    _context.Response.ContentType 
= mimeMap[System.IO.Path.GetExtension(fileName).ToLower()].ToString();
                }

                
catch
                
{
                    _context.Response.ContentType 
= "application/octet-stream";
                }


                _context.Response.AddHeader(
"Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode("Spider_FileDown_"+fileName, System.Text.Encoding.UTF8));
                _context.Response.AddHeader(
"Content-Length", toDownload.Length.ToString());

                _context.Response.Write(_context.Response.ContentType);
               
/* 块读取
                using(FileStream iStream   = File.OpenRead(path))
                {
                    long ReadFileLength =  iStream.Length;
                    long lengthRead = 0;
                    while(ReadFileLength > 0 && _context.Response.IsClientConnected)
                    {
                        lengthRead = iStream.Read(buffer, 0, (int)DownFileBufferSize);
                       
                      //  _context.Response.TransmitFile(path, oldReaded, DownFileBufferSize);

                        oldReaded = lengthRead + oldReaded;
                        ReadFileLength = ReadFileLength - lengthRead;
                    }
                }
                
*/

                _context.Response.TransmitFile(path);
            }

            
else 
            
{
                _context.Response.Write(
"<script language='javascript'>alert('File Not Exists!')</script>");
            }


            _context.Response.End();
           
            _completed 
= true;
            _callback(
this);
        }

    }

}


HttpAsyncHandler 处理类

using System;
using System.Web;
using System.Threading;

namespace Spider.Model.AsyncNoCacheDown
{
    
class HttpAsyncDownLoadHandler : IHttpAsyncHandler
    
{

        
public bool IsReusable get return false; } }

        
public HttpAsyncDownLoadHandler()
        
{
        }

        
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
        
{
            context.Response.Write(
"<p>Begin IsThreadPoolThread is " + Thread.CurrentThread.IsThreadPoolThread + "</p>\r\n");

            AsynchOperation asynch 
= new AsynchOperation(cb, context, extraData);
            asynch.StartAsyncWork();
            
return asynch;
        }


        
public void EndProcessRequest(IAsyncResult result)
        
{
        }


        
public void ProcessRequest(HttpContext context)
        
{
            
throw new InvalidOperationException();
        }

    }

}


不要忘了在web.config文件中加入下面代码哟
<httpHandlers>
   <add verb="*" path="DownFile.axd" type="Spider.Model.AsyncNoCacheDown.HttpAsyncDownLoadHandler,Spider.Model"/>
  </httpHandlers>

仅供学习参考^o^
posted @ 2007-11-09 17:42  auspicious  阅读(377)  评论(0)    收藏  举报