Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示。不过官方提供的实例时php版本的,本文将详细介绍 Uploadify在Aspnet中的使用。

  首先按下面的步骤来实现一个简单的上传功能。

  1 创建Web项目,命名为JQueryUploadDemo,从官网上下载最新的版本解压后添加到项目中。

  2 在项目中添加UploadHandler.ashx文件用来处理文件的上传。

  3 在项目中添加UploadFile文件夹,用来存放上传的文件。

  进行完上面三步后项目的基本结构如下图:

  4 Default.aspx的html页的代码修改如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Uploadify</title>
    <link href="JS/jquery.uploadify-v2.1.0/example/css/default.css"
     rel="stylesheet" type="text/css" />
    <link href="JS/jquery.uploadify-v2.1.0/uploadify.css"
     rel="stylesheet" type="text/css" />
    <script type="text/javascript"
     src="JS/jquery.uploadify-v2.1.0/jquery-1.3.2.min.js"></script>
    <script type="text/javascript"
     src="JS/jquery.uploadify-v2.1.0/swfobject.js"></script>
    <script type="text/javascript"
   src="JS/jquery.uploadify-v2.1.0/jquery.uploadify.v2.1.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $("#uploadify").uploadify({
                'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf',
                'script': 'UploadHandler.ashx',
                'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png',
                'folder': 'UploadFile',
                'queueID': 'fileQueue',
                'auto': false,
                'multi': true
            });
        });  
    </script>
</head>
<body>
    <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
      <a href="javascript:$('#uploadify').uploadifyUpload()">上传</a>| 
      <a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上传</a& gt;
    </p>
</body>
</html>


  5 UploadHandler类的ProcessRequest方法代码如下:


  public void ProcessRequest(HttpContext context)
  {
  context.Response.ContentType = "text/plain";
  context.Response.Charset = "utf-8";
  HttpPostedFile file = context.Request.Files["Filedata"];
  string uploadPath =
  HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";
  if (file != null)
  {
  if (!Directory.Exists(uploadPath))
  {
  Directory.CreateDirectory(uploadPath);
  }
  file.SaveAs(uploadPath + file.FileName);
  //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
  context.Response.Write("1");
  }
  else
  {
  context.Response.Write("0");
  }
  }

      6 运行后效果如下图:

  7 选择了两个文件后,点击上传,就可以看到UploadFile文件夹中会增加这两个文件。

  上面简单地实现了一个上传的功能,依靠函数uploadify实现,uploadify函数的参数为json格式,可以对json对象的key 值的修改来进行自定义的设置,如multi设置为true或false来控制是否可以进行多文件上传,下面就来介绍下这些key值的意思:

  uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf。

  script : 后台处理程序的相对路径 。默认值:uploadify.php

  checkScript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径

  fileDataName :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata

  method : 提交方式Post 或Get 默认为Post

  scriptAccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain

  folder : 上传文件存放的目录 。

  queueID : 文件队列的ID,该ID与存放文件队列的div的ID一致。

  queueSizeLimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。

  multi : 设置为true时可以上传多个文件。

  auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。

  fileDesc : 这个属性值必须设置fileExt属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileDesc为“请选择rar doc pdf文件”,打开文件选择框效果如下图:

  fileExt : 设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。

  sizeLimit : 上传文件的大小限制 。

  simUploadLimit : 允许同时上传的个数 默认值:1 。

  buttonText : 浏览按钮的文本,默认值:BROWSE 。

  buttonImg : 浏览按钮的图片的路径 。

  hideButton : 设置为true则隐藏浏览按钮的图片 。

  rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。

  width : 设置浏览按钮的宽度 ,默认值:110。

  height : 设置浏览按钮的高度 ,默认值:30。

  wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。

  cancelImg :选择文件到文件队列中后的每一个文件上的关闭按钮图标,如下图:

  上面介绍的key值的value都为字符串或是布尔类型,比较简单,接下来要介绍的key值的value为一个函数,可以在选择文件、出错或其他一些操作的时候返回一些信息给用户。

  onInit : 做一些初始化的工作。

  onSelect :选择文件时触发,该函数有三个参数

  event:事件对象。

  queueID:文件的唯一标识,由6为随机字符组成。

  fileObj:选择的文件对象,有name、size、creationDate、modificationDate、type 5个属性。

  代码如下:


  $(document).ready(function()
  {
  $("#uploadify").uploadify({
  'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf',
  'script': 'UploadHandler.ashx',
  'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png',
  'folder': 'UploadFile',
  'queueID': 'fileQueue',
  'auto': false,
  'multi': true,
  'onInit':function(){alert("1");},
  'onSelect': function(e, queueId, fileObj)
  {
  alert("唯一标识:" + queueId + "\r\n" +
  "文件名:" + fileObj.name + "\r\n" +
  "文件大小:" + fileObj.size + "\r\n" +
  "创建时间:" + fileObj.creationDate + "\r\n" +
  "最后修改时间:" + fileObj.modificationDate + "\r\n" +
  "文件类型:" + fileObj.type
  );
  }
  });
  }); 


      当选择一个文件后弹出的消息如下图:

  onSelectOnce :在单文件或多文件上传时,选择文件时触发。该函数有两个参数event,data,data对象有以下几个属性:

  fileCount:选择文件的总数。

  filesSelected:同时选择文件的个数,如果一次选择了3个文件该属性值为3。

  filesReplaced:如果文件队列中已经存在A和B两个文件,再次选择文件时又选择了A和B,该属性值为2。

  allBytesTotal:所有选择的文件的总大小。

  onCancel : 当点击文件队列中文件的关闭按钮或点击取消上传时触发。该函数有event、queueId、fileObj、data四个参数,前三个参数同 onSelect 中的三个参数,data对象有两个属性fileCount和allBytesTotal。

  fileCount:取消一个文件后,文件队列中剩余文件的个数。

  allBytesTotal:取消一个文件后,文件队列中剩余文件的大小。

  onClearQueue :当调用函数fileUploadClearQueue时触发。有event和data两个参数,同onCancel 中的两个对应参数。

  onQueueFull :当设置了queueSizeLimit并且选择的文件个数超出了queueSizeLimit的值时触发。该函数有两个参数event和 queueSizeLimit。

  onError :当上传过程中发生错误时触发。该函数有event、queueId、fileObj、errorObj四个参数,其中前三个参数同上,errorObj 对象有type和info两个属性。

  type:错误的类型,有三种‘HTTP’, ‘IO’, or ‘Security’

  info:错误的描述

  onOpen :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列。该函数有event、queueId、 fileObj三个参数,参数的解释同上。

  onProgress :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列,在onOpen之后触发。该函数有 event、queueId、fileObj、data四个参数,前三个参数的解释同上。data对象有四个属性percentage、 bytesLoaded、allBytesLoaded、speed:

  percentage:当前完成的百分比

  bytesLoaded:当前上传的大小

  allBytesLoaded:文件队列中已经上传完的大小

  speed:上传速率 kb/s

  onComplete:文件上传完成后触发。该函数有四个参数event、queueId、fileObj、response、data五个参数,前三个参数同上。response为后台处理程序返回的值,在上面的例子中为1或0,data有两个属性fileCount和speed

  fileCount:剩余没有上传完成的文件的个数。

  speed:文件上传的平均速率 kb/s

  onAllComplete:文件队列中所有的文件上传完成后触发。该函数有event和data两个参数,data有四个属性,分别为:

  filesUploaded :上传的所有文件个数。

  errors :出现错误的个数。

  allBytesLoaded :所有上传文件的总大小。

  speed :平均上传速率 kb/s

  相关函数介绍

  在上面的例子中已经用了uploadifyUpload和uploadifyClearQueue两个函数,除此之外还有几个函数:

  uploadifySettings:可以动态修改上面介绍的那些key值,如下面代码:

  $('#uploadify').uploadifySettings('folder','JS');如果上传按钮的事件写成下面这样,文件将会上传到uploadifySettings定义的目录中

  上传uploadifyCancel:该函数接受一个queueID作为参数,可以取消文件队列中指定queueID的文件。

  $('#uploadify').uploadifyCancel(id);花了一个晚上,终于写完了,对JQuery这个上传插件也基本了解了,希望对大家有所帮助,不对之处还望大家指正

posted @ 2010-07-13 13:41 JV Studio 阅读(43) 评论(0) 编辑

前言

本文是我对ASP.NET页面载入速度提高的一些做法,这些做法分为以下部分:

1.采用 HTTP Module 控制页面的生命周期。

2.自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存)。

3.页面GZIP压缩。

4.OutputCache 编程方式输出页面缓存。

5.删除页面空白字符串。(类似Google)

6.完全删除ViewState。

7.删除服务器控件生成的垃圾NamingContainer。

8.使用计划任务按时生成页面。(本文不包含该做法的实现)

9.JS,CSS压缩、合并、缓存,图片缓存。(限于文章篇幅,本文不包含该做法的实现)

10.缓存破坏。(不包含第9做法的实现)

针对上述做法,我们首先需要一个 HTTP 模块,它是整个页面流程的入口和核心。

一、自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存)

如下的代码我们可以看出,我们以 request.RawUrl 为缓存基础,因为它可以包含任意的QueryString变量,然后我们用MD5加密RawUrl 得到服务器本地文件名的变量,再实例化一个FileInfo操作该文件,如果文件最后一次生成时间小于7天,我们就使用.Net2.0新增的 TransmitFile方法将存储文件的静态内容发送到浏览器。如果文件不存在,我们就操作 response.Filter 得到的 Stream 传递给 CommonFilter 类,并利用FileStream写入动态页面的内容到静态文件中。

  1. namespace  ASPNET_CL.Code.HttpModules {  
  2.      public  class  CommonModule : IHttpModule {  
  3.          public  void  Init( HttpApplication application ) {  
  4.             application.BeginRequest += Application_BeginRequest;  
  5.         }  
  6.  
  7.          private  void  Application_BeginRequest(  object  sender, EventArgs e ) {  
  8.             var context = HttpContext.Current;  
  9.             var request = context.Request;  
  10.             var url = request.RawUrl;  
  11.  
  12.             var response = context.Response;  
  13.             var path = GetPath( url );  
  14.             var file =  new  FileInfo( path );  
  15.  
  16.              if  ( DateTime.Now.Subtract( file.LastWriteTime ).TotalDays < 7 ) {  
  17.                 response.TransmitFile( path );  
  18.                 response.End();  
  19.                  return;  
  20.             }  
  21.              try  {  
  22.                 var stream = file.OpenWrite();  
  23.                 response.Filter =  new  CommonFilter( response.Filter, stream );  
  24.             }  
  25.              catch  ( Exception ) {  
  26.                  //Log.Insert("");  
  27.             }  
  28.         }  
  29.  
  30.          public  void  Dispose() {  
  31.  
  32.         }  
  33.  
  34.          private  static  string  GetPath(  string  url ) {  
  35.             var hash = Hash( url );  
  36.              string  fold = HttpContext.Current.Server.MapPath(  "~/Temp/"  );  
  37.              return  string.Concat( fold, hash );  
  38.         }  
  39.  
  40.          private  static  string  Hash(  string  url ) {  
  41.             url = url.ToUpperInvariant();  
  42.             var md5 =  new  System.Security.Cryptography.MD5CryptoServiceProvider();  
  43.             var bs = md5.ComputeHash( Encoding.ASCII.GetBytes( url ) );  
  44.             var s =  new  StringBuilder();  
  45.              foreach  ( var b  in  bs ) {  
  46.                 s.Append( b.ToString(  "x2"  ).ToLower() );  
  47.             }  
  48.              return  s.ToString();  
  49.         }  
  50.     }  

二、页面GZIP压缩

对页面GZIP压缩几乎是每篇讲解高性能WEB程序的几大做法之一,因为使用GZIP压缩可以降低服务器发送的字节数,能让客户感觉到网页的速度更快也减少了对带宽的使用情况。当然,这里也存在客户端的浏览器是否支持它。因此,我们要做的是,如果客户端支持GZIP,我们就发送GZIP压缩过的内容,如果不支持,我们直接发送静态文件的内容。幸运的是,现代浏览器IE6.7.8.0,火狐等都支持GZIP。

为了实现这个功能,我们需要改写上面的 Application_BeginRequest 事件:

  1.  private void Application_BeginRequest( object sender, EventArgs e ) {  
  2.     var context = HttpContext.Current;  
  3.     var request = context.Request;  
  4.     var url = request.RawUrl;  
  5.  
  6.     var response = context.Response;  
  7.     var path = GetPath( url );  
  8.     var file = new FileInfo( path );  
  9.  
  10.     // 使用页面压缩  
  11.       ResponseCompressionType compressionType = this.GetCompressionMode( request );  
  12.     if ( compressionType != ResponseCompressionType.None ) {  
  13.         response.AppendHeader( "Content-Encoding", compressionType.ToString().ToLower() );  
  14.         if ( compressionType == ResponseCompressionType.GZip ) {  
  15.             response.Filter = new GZipStream( response.Filter, CompressionMode.Compress );  
  16.         }  
  17.         else {  
  18.             response.Filter = new DeflateStream( response.Filter, CompressionMode.Compress );  
  19.         }  
  20.     }  
  21.  
  22.     if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {  
  23.         response.TransmitFile( path );  
  24.         response.End();  
  25.         return;  
  26.     }  
  27.     try {  
  28.         var stream = file.OpenWrite();  
  29.         response.Filter = new CommonFilter( response.Filter, stream );  
  30.     }  
  31.     catch ( Exception ) {  
  32.         //Log.Insert("");  
  33.     }  
  34. }  
  35.  
  36. private ResponseCompressionType GetCompressionMode( HttpRequest request ) {  
  37.     string acceptEncoding = request.Headers[ "Accept-Encoding" ];  
  38.     if ( string.IsNullOrEmpty( acceptEncoding ) )  
  39.         return ResponseCompressionType.None;  
  40.  
  41.     acceptEncoding = acceptEncoding.ToUpperInvariant();  
  42.  
  43.     if ( acceptEncoding.Contains( "GZIP" ) )  
  44.         return ResponseCompressionType.GZip;  
  45.     else if ( acceptEncoding.Contains( "DEFLATE" ) )  
  46.         return ResponseCompressionType.Deflate;  
  47.     else 
  48.         return ResponseCompressionType.None;  
  49. }  
  50.  
  51. private enum ResponseCompressionType {  
  52.     None,  
  53.     GZip,  
  54.     Deflate  

三、OutputCache 编程方式输出页面缓存

ASP.NET内置的 OutputCache 缓存可以将内容缓存在三个地方:Web服务器、代理服务器和浏览器。当用户访问一个被设置为 OutputCache的页面时,ASP.NET在MSIL之后,先将结果写入output cache缓存,然后在发送到浏览器,当用户访问同一路径的页面时,ASP.NET将直接发送被Cache的内容,而不经过.aspx编译以及执行 MSIL的过程,所以,虽然程序的本身效率没有提升,但是页面载入速度却得到了提升。

为了实现这个功能,我们继续改写上面的 Application_BeginRequest 事件,我们在 TransmitFile 后,将这个路径的页面以OutputCache编程的方式缓存起来:

  1. private void Application_BeginRequest( object sender, EventArgs e ) {  
  2.            
  3.            //.............  
  4.  
  5.             if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {  
  6.                 response.TransmitFile( path );  
  7.                 // 添加 OutputCache 缓存头,并缓存在客户端  
  8.                   response.Cache.SetExpires( DateTime.Now.AddMinutes( 5 ) );  
  9.                 response.Cache.SetCacheability( HttpCacheability.Public );  
  10.                 response.End();  
  11.                 return;  
  12.             }  
  13.              
  14.            //............  
  15.  } 

四、实现CommonFilter类过滤ViewState、过滤NamingContainer、空白字符串,以及生成磁盘的缓存文件

我们传入response.Filter的Stream对象给CommonFilter类:

首先,我们用先Stream的Write方法实现生成磁盘的缓存文件,代码如下,在这些代码中,只有初始化构造函数,Write方法,Close方式是有用的,其中FileStream字段是生成静态文件的操作对象:

  1. namespace ASPNET_CL.Code.HttpModules {  
  2.     public class CommonFilter : Stream {  
  3.         private readonly Stream _responseStream;  
  4.         private readonly FileStream _cacheStream;  
  5.  
  6.         public override bool CanRead {  
  7.             get {  
  8.                 return false;  
  9.             }  
  10.         }  
  11.         public override bool CanSeek {  
  12.             get {  
  13.                 return false;  
  14.             }  
  15.         }  
  16.         public override bool CanWrite {  
  17.             get {  
  18.                 return _responseStream.CanWrite;  
  19.             }  
  20.         }  
  21.         public override long Length {  
  22.             get {  
  23.                 throw new NotSupportedException();  
  24.             }  
  25.         }  
  26.         public override long Position {  
  27.             get {  
  28.                 throw new NotSupportedException();  
  29.             }  
  30.             set {  
  31.                 throw new NotSupportedException();  
  32.             }  
  33.         }  
  34.  
  35.         public CommonFilter( Stream responseStream, FileStream stream ) {  
  36.             _responseStream = responseStream;  
  37.             _cacheStream = stream;  
  38.         }  
  39.  
  40.         public override long Seek( long offset, SeekOrigin origin ) {  
  41.             throw new NotSupportedException();  
  42.         }  
  43.         public override void SetLength( long length ) {  
  44.             throw new NotSupportedException();  
  45.         }  
  46.         public override int Read( byte[] buffer, int offset, int count ) {  
  47.             throw new NotSupportedException();  
  48.         }  
  49.         public override void Flush() {  
  50.             _responseStream.Flush();  
  51.             _cacheStream.Flush();  
  52.         }  
  53.         public override void Write( byte[] buffer, int offset, int count ) {  
  54.             _cacheStream.Write( buffer, offset, count );  
  55.             _responseStream.Write( buffer, offset, count );  
  56.         }  
  57.         public override void Close() {  
  58.             _responseStream.Close();  
  59.             _cacheStream.Close();  
  60.         }  
  61.         protected override void Dispose( bool disposing ) {  
  62.             if ( disposing ) {  
  63.                 _responseStream.Dispose();  
  64.                 _cacheStream.Dispose();  
  65.             }  
  66.         }  
  67.     }  

然后我们利用正则完全删除ViewState:

  1. // 过滤ViewState  
  2.  private string ViewStateFilter( string strHTML ) {  
  3.      string matchString1 = "type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\"";  
  4.      string matchString2 = "type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\"";  
  5.      string matchString3 = "type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\"";  
  6.      string matchString4 = "type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\"";  
  7.  
  8.      string positiveLookahead1 = "(?=.*(" + Regex.Escape( matchString1 ) + "))";  
  9.      string positiveLookahead2 = "(?=.*(" + Regex.Escape( matchString2 ) + "))";  
  10.      string positiveLookahead3 = "(?=.*(" + Regex.Escape( matchString3 ) + "))";  
  11.      string positiveLookahead4 = "(?=.*(" + Regex.Escape( matchString4 ) + "))";  
  12.  
  13.      RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;  
  14.  
  15.      Regex[] arrRe = new Regex[] {  
  16.          new Regex("\\s*<div>" + positiveLookahead1 + "(.*?)</div>\\s*", opt),  
  17.          new Regex("\\s*<div>" + positiveLookahead2 + "(.*?)</div>\\s*", opt),  
  18.          new Regex("\\s*<div>" + positiveLookahead3 + "(.*?)</div>\\s*", opt),  
  19.          new Regex("\\s*<div>" + positiveLookahead3 + "(.*?)</div>\\s*", opt),  
  20.          new Regex("\\s*<div>" + positiveLookahead4 + "(.*?)</div>\\s*", opt)  
  21.      };  
  22.  
  23.      foreach ( Regex re in arrRe ) {  
  24.          strHTML = re.Replace( strHTML, "" );  
  25.      }  
  26.      return strHTML;  
  27.  } 

以下是删除页面空白的方法:

  1. // 删除空白  
  2.   private Regex tabsRe = new Regex( "\\t", RegexOptions.Compiled | RegexOptions.Multiline );  
  3.  private Regex carriageReturnRe = new Regex( ">\\r\\n<", RegexOptions.Compiled | RegexOptions.Multiline );  
  4.  private Regex carriageReturnSafeRe = new Regex( "\\r\\n", RegexOptions.Compiled | RegexOptions.Multiline );  
  5.  private Regex multipleSpaces = new Regex( "  ", RegexOptions.Compiled | RegexOptions.Multiline );  
  6.  private Regex spaceBetweenTags = new Regex( ">\\s<", RegexOptions.Compiled | RegexOptions.Multiline );  
  7.  private string WhitespaceFilter( string html ) {  
  8.      html = tabsRe.Replace( html, string.Empty );  
  9.      html = carriageReturnRe.Replace( html, "><" );  
  10.      html = carriageReturnSafeRe.Replace( html, " " );  
  11.  
  12.      while ( multipleSpaces.IsMatch( html ) )  
  13.          html = multipleSpaces.Replace( html, " " );  
  14.  
  15.      html = spaceBetweenTags.Replace( html, "><" );  
  16.  
  17.      html = html.Replace( "//<![CDATA[""" );  
  18.      html = html.Replace( "//]]>""" );  
  19.  
  20.      return html;  
  21.  } 

以下是删除ASP.NET控件的垃圾UniqueID名称方法:

  1.         // 过滤NamingContainer  
  2. private string NamingContainerFilter( string html ) {  
  3.             RegexOptions opt =  
  4.                 RegexOptions.IgnoreCase |  
  5.                 RegexOptions.Singleline |  
  6.                 RegexOptions.CultureInvariant |  
  7.                 RegexOptions.Compiled;  
  8. Regex re = new Regex( "( name=\")(?=.*(" + Regex.Escape( "$" ) + "))([^\"]+?)(\")", opt );  
  9. html = re.Replace( html, new MatchEvaluator( delegate( Match m ) {  
  10.                 int lastDollarSignIndex = m.Value.LastIndexOf( '$' );  
  11. if ( lastDollarSignIndex >= 0 ) {  
  12. return m.Groups[ 1 ].Value + m.Value.Substring( lastDollarSignIndex + 1 );  
  13.                 }  
  14.                 else {  
  15.                     return m.Value;  
  16.                 }  
  17.             } ) );  
  18.  
  19.             return html;  
  20.         } 

最后,我们把以上过滤方法整合到CommonFilter类的Write方法:

  1. public override void Write( byte[] buffer, int offset, int count ) {  
  2.     // 转换buffer为字符串  
  3.     byte[] data = new byte[ count ];  
  4.     Buffer.BlockCopy( buffer, offset, data, 0, count );  
  5.     string html = System.Text.Encoding.UTF8.GetString( buffer );  
  6.  
  7.     //  
  8.     // 以下整合过滤方法  
  9.      //  
  10.  
  11.     html = NamingContainerFilter( html );  
  12.     html = ViewStateFilter( html );  
  13.     html = WhitespaceFilter( html );  
  14.  
  15.     byte[] outdata = System.Text.Encoding.UTF8.GetBytes( html );  
  16.  
  17.     // 写入磁盘  
  18.     _cacheStream.Write( outdata, 0, outdata.GetLength( 0 ) );  
  19.     _responseStream.Write( outdata, 0, outdata.GetLength( 0 ) );  

五、缓存破坏

经过以上程序的实现,网页已经被高速缓存在客户端了,如果果用户访问网站被缓存过的页面,则页面会以0请求的速度加载页面。但是,如果后台更新了某些数据,前台用户则不能及时看到最新的数据,因此要改变这种情况,我们必须破坏缓存。根据我们如上的程序,我们破坏缓存只需要做2步:更新服务器上的临时文件,删除OutputCache过的页面。

更新服务器上的文件我们只需删除这个文件即可,当某一用户第一次访问该页面时会自动生成,当然,你也可以用程序先删除后生成:

  1. // 更新文件  
  2. foreach ( var file in Directory.GetFiles( HttpRuntime.AppDomainAppPath + "Temp" ) ) {  
  3.     File.Delete( file );  

要删除OutputCache关联的缓存项,代码如下,我们只需要保证该方法的参数,指页面的绝对路径是正确的,路径不能使用../这样的相对路径:

  1. // 删除缓存  
  2. HttpResponse.RemoveOutputCacheItem( "/Default.aspx" ); 

 

到此,我们实现了针对一个页面的性能,重点是载入速度的提高的一些做法,希望对大家有用~!

posted @ 2010-07-13 13:40 JV Studio 阅读(19) 评论(0) 编辑
posted @ 2010-07-13 13:40 JV Studio 阅读(15) 评论(0) 编辑