【问题标题】:Using Stream to display Image *.ico使用 Stream 显示图像 *.ico
【发布时间】:2012-03-19 14:34:17
【问题描述】:

我想显示带有扩展名*.ico 的图像,我使用Stream 来执行此操作。但我有一个问题。

带有扩展名*.jpg*.bmp...图片显示正常,但*.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();
            }
        }
    }

请帮我解决这个问题。

【问题讨论】:

  • 代码看起来不错(奇怪地覆盖了 SP 安全性,并且不清楚为什么当它们应该已经可以通过 url 访问时,你为什么要尝试手动流式传输文件......)。在服务器上获取文件流或在浏览器中呈现是否有问题(我不希望 ICO 呈现为 IMG 标签)

标签: c# asp.net stream


【解决方案1】:

您没有在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";

【讨论】:

  • @user1186850 很高兴我能帮上忙!
猜你喜欢
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
  • 2016-12-17
  • 2012-12-03
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
相关资源
最近更新 更多