我有幾個方法來處理使用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);
}
[MiscUtil](http://www.yoda.arachsys.com/csharp/miscutil/)中有一個完全實現的裝飾器 - 「NonClosingStreamWrapper」或類似的。 – 2011-02-01 14:26:02