1

我正在使用 fileuplaod 控件来上传图像。为此,我曾经将其存储在缓存中

以字节格式显示 2 小时,并使用 .ashx 文件中的 HttpContext 显示此图像。出于某种原因

有时会保存在缓存中,有时不会。我正在使用 asp.net 2.0 和 C# 语言。

我的保存代码:

//Name of the Image 
string strGuid = Guid.NewGuid().ToString(); 
byte[] byteImage = new byte[ImageUpload.PostedFile.ContentLength];

//file upload control ID "ImageUpload" and read it and save it in cache.
ImageUpload.PostedFile.InputStream.Read(byteImage, 0, byteImage.Length);

//Saving Byte in the cache
Cache.Add(strGuid, byteImage, null, DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

//Saving Image Format in cache
Cache.Add(string.Format("{0}_Type", strGuid), strContentType, null, DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
UserImage.ImageUrl = string.Format("~/UserControl/ImageHander.ashx?imgId={0}", strGuid);

使用 .ashx 文件渲染图像的代码:

public void ProcessRequest (HttpContext context) 
{
    string strImageGuid = context.Request.QueryString["imgId"].ToString();
    string strContentTypeID = string.Format("{0}_Type",  context.Request.QueryString["imgId"].ToString());
    byte[] byteImage =(byte []) context.Cache[strImageGuid];
    string strContentType = (string)context.Cache[strContentTypeID];
    context.Response.ContentType = strContentType;
    context.Response.OutputStream.Write(byteImage, 0, byteImage.Length);
}

将字节图像保存在缓存中是否有任何问题或任何其他更好的方法?

谢谢!桑杰帕尔

4

2 回答 2

4

不能保证在缓存中找到放入缓存的项目。在某些情况下,框架可能会使缓存中的项目过期,例如,如果它开始内存不足。在这种情况下,当您将项目添加到缓存时,它将调用您传递的onRemoveCallback 。

缓存不是可靠的存储,您需要在使用它之前始终检查该项目是否存在,如果它没有执行必要的操作来获取它并将其放回那里,以便将来的调用者可以找到它。

于 2009-11-07T13:46:05.203 回答
1

您可以指定 CacheItemPriority.NotRemovable 而不是 CacheItemPriority.Normal 以防止它在到期之前从缓存中删除。

但是更传统的方法是允许它被删除,如果你发现它丢失了重新填充缓存。

于 2009-11-07T14:36:34.617 回答