2011-02-01 54 views
2

我有幾個方法來處理使用Request.InputStream保存圖像。我有兩個共享HttpContext的擴展。在我的一個方法中,我使用BinaryReader來讀取內容並執行處理。但是,當處理BinaryReader時,它自然會關閉Request上的InputStream屬性。我的SECOND方法使用相同的輸入流來創建縮略圖。基本上,我需要一種方法來在第一種方法中處理讀取器之後保持Request.InputStream屬性處於活動狀態。這可能嗎?這是我的兩種方法。首先調用SaveImageStream(),然後調用GenerateThumbnail()。爲了使Request.InputStream保持活動狀態,讓一個BinaryReader對象未處理?

public static void SaveImageStream(this HttpContextBase ctx, string filename) 
{ 
    var config = ObjectFactory.GetInstance<IConfig>(); 

    using (var reader = new BinaryReader(ctx.Request.InputStream)) 
    { 
     var bandImagesPath = config.GetSetting<string>("BandImagePath"); 
     var path = Path.Combine(ctx.Server.MapPath(bandImagesPath), filename); 

     byte[] file = reader.ReadBytes((int)ctx.Request.InputStream.Length); 

     using (var outputStream = System.IO.File.Create(path, 2048)) 
     { 
      const int chunkSize = 2 * 1024; // 2KB 
      byte[] buffer = new byte[chunkSize]; 
      int bytesRead; 
      ctx.Request.InputStream.Position = 0; 
      while ((bytesRead = ctx.Request.InputStream.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       outputStream.Write(buffer, 0, bytesRead); 
      } 
     } 
    } 
} 

public static void GenerateThumbnail(this HttpContextBase ctx, string filename) 
{ 
    var config = ObjectFactory.GetInstance<IConfig>(); 

    int size = config.GetSetting<int>("ThumbSize"); 
    var thumbPath = Path.Combine(ctx.Server.MapPath(config.GetSetting<string>("ThumbPath")), filename); 

    var image = System.Drawing.Image.FromStream(ctx.Request.InputStream); 
    var thumb = image.GetThumbnailImage(size, size, null, IntPtr.Zero); 

    thumb.Save(thumbPath, System.Drawing.Imaging.ImageFormat.Png); 
} 

回答

0

通過調用另外一個方法,你可以做using語句中的一切。我也想知道這個行:

byte[] file = reader.ReadBytes((int)ctx.Request.InputStream.Length); 

您沒有使用file變量的任何地方,裏面有整個請求流駐留在內存中。如果你不小心這將是一個拒絕服務攻擊的途徑。但到解決方案...

更改縮略圖的方法是這樣的:

public static void SaveImageStream(this HttpContextBase ctx, string filename) 
{ 
    var config = ObjectFactory.GetInstance<IConfig>(); 

    using (var reader = new BinaryReader(ctx.Request.InputStream)) 
    { 
     var bandImagesPath = config.GetSetting<string>("BandImagePath"); 
     var path = Path.Combine(ctx.Server.MapPath(bandImagesPath), filename); 

     using (var outputStream = System.IO.File.Create(path, 2048)) 
     { 
      const int chunkSize = 2 * 1024; // 2KB 
      byte[] buffer = new byte[chunkSize]; 
      int bytesRead; 
      ctx.Request.InputStream.Position = 0; 
      while ((bytesRead = ctx.Request.InputStream.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       outputStream.Write(buffer, 0, bytesRead); 
      } 
     } 

     ctx.Request.InputStream.Position = 0; 
     ctx.GenerateThumbnail(filename); 
    } 
} 

或者,你可以使用一個MemoryStream周圍file屬性,併發送至GenerateThumbnail擴展方法。

相關問題