2012-03-01 37 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