2012-03-01 63 views
6

我想显示图像的扩展名为*.ico,我用Stream来做到这一点。但我有一个问题。使用流来显示图像* .ico

带延伸*.jpg*.bmp ...图片显示OK,但*.ico,它并不显示

这里是我的代码:

private void OutputStream(string fileName) 
    { 
     try 
     { 
      Stream dataStream = null; 

       SPSecurity.RunWithElevatedPrivileges(delegate() 
       { 
        SPFile spFile = web.GetFile(fileName); 
        dataStream = spFile.OpenBinaryStream(); 
        this.HandleOutputStream(dataStream); 
       }); 

     } 
     catch (System.Threading.ThreadAbortException exTemp) 
     { 
      logger.Error("KBStreamPicture::OutputStream", exTemp); 
     } 
     catch (Exception ex) 
     { 
      //System.Diagnostics.Debug.Write("OutputStream::" + ex); 
      logger.Error("KBStreamPicture::OutputStream", ex); 
     } 
    } 

private void HandleOutputStream(Stream dataStream) 
    { 
     const int bufferSize = 16384; //16KB 

     using (Stream file = dataStream) 
     { 
      if (file != null) 
      { 
       this.Page.Response.Clear(); 
       this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private); 
       this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20)); //only cache 20 minutes 
       byte[] buffer = new byte[bufferSize]; 
       int count = file.Read(buffer, 0, bufferSize); 

       while (count > 0) 
       { 
        if (this.Page.Response.IsClientConnected) 
        { 
         this.Page.Response.OutputStream.Write(buffer, 0, count); 
         count = file.Read(buffer, 0, bufferSize); 
        } 
        else 
        { 
         count = -1; 
        } 
       } 
       this.Page.Response.End(); 
      } 
     } 
    } 

请帮我解决这个问题。

+0

代码看起来不错(SP安全怪替换,不清楚为什么你会尝试通过用手往下流文件时,他们应该已经通过URL访问... )。你有没有在服务器上获取文件流或在浏览器中渲染的问题(我不希望ICO渲染为IMG标签) – 2012-03-01 04:14:17

回答

4

您并未在Response上设置ContentType属性。尝试将ContentType设置为image/x-icon(请注意,“正确”的内容类型可能为image/vnd.microsoft.icon,但this post似乎表明您可能遇到该类型的问题)。

的代码应该是这个样子:

this.Page.Response.Clear(); 
this.Page.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private); 
this.Page.Response.Cache.SetExpires(DateTime.Now.AddMinutes(20)); 
this.Page.Response.ContentType = "image/x-icon"; 
+0

感谢您的帮助。我为我工作得很好。 – user1186850 2012-03-01 06:52:58

+0

'用户'标记作为答案,如果它的工作 – Dotnet 2012-03-01 12:27:56

+0

@ user1186850很高兴我可以帮助! – rsbarro 2012-03-01 14:38:10