【问题标题】:Returning image as FileContentResult .net将图像作为 FileContentResult .net 返回
【发布时间】:2014-11-29 22:22:51
【问题描述】:

我基本上是在尝试从服务器上的方法将图像返回给客户端。它适用于除 IE 之外的所有浏览器(仅尝试过 IE 11,但猜测旧版本的浏览器相同)。

基本上这就是我在服务器上所做的:

public FileContentResult GetIconForFileExtention(string fileExtention, bool largeIcon = true)
{
    if (!fileExtention.StartsWith("."))
    {
        fileExtention = "." + fileExtention;
    }

    using (IconContainer icon = ShellIcons.GetIconForFile(fileExtention, true, largeIcon))
    {
        Bitmap b = icon.Icon.ToBitmap();             
        MemoryStream ms = new MemoryStream();
        icon.Icon.Save(ms);

        FileContentResult image = null;
        try
        {
            image = File(ms.ToArray(), "image/png", "icon");
        }
        catch (Exception e)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(e);
        }

        return image;
     }
}    

这是一个 .net mvc 应用程序。在客户端上,我只需将图像加载到 img 标签中,如下所示:

<img src="@Url.Action("GetIconForFileExtention", "MyDocuments", new { fileExtention = "odt" })" />

非常感谢任何帮助。

【问题讨论】:

  • 按 F12,看看浏览器告诉你什么。
  • 我已经在网络检查器中检查了请求和响应,并且图像加载正常。我可以在列表中看到图像,您可以在其中看到所有下载时间等。我刚刚注销了 Windows 机器,稍后可以再次登录并发布请求和响应标头,如果这有帮助的话。
  • 那什么“不起作用”?你预计会发生什么,你看到了什么?
  • 我可能倾向于内容类型或编码问题?图片内容类型设置为 image/png 是否需要设置其他内容?
  • 图像未在页面上呈现。只是“X”符号。

标签: c# html .net asp.net-mvc


【解决方案1】:

我认为您的操作和剃刀代码是正确的,我会尝试检查您的 GetIconForFile 方法并确保它正确返回图标。

这段代码应该可以在不使用上述方法的情况下正确地将图标填充为FileContentResult

FileContentResult image = null;

var icon = Icon.ExtractAssociatedIcon(Server.MapPath("~") + "/favicon.ico");

using (var ms = new MemoryStream())
{
    icon.Save(ms);
    image = File(ms.ToArray(), "image/png", "icon");
}

return image;

您可以尝试运行它并确认问题不在 Action 和 Razor 视图中,而是在 ShellIcons 类中。在运行它之前,请确保您的根文件夹中有一个“favicon.ico”;)

【讨论】:

  • 抱歉重播晚了。第二个jobb打电话。我确实尝试了您的测试,但不是图标。它在 chrome ie11 上运行良好仍然失败。在我得到之前是否忽略了控制台输出:“无法在 URL 解码图像:”任何 ide?​​span>
  • 发现问题。图标.图标.保存(毫秒);不知何故弄乱了编码。解决方案将该行更改为 b.Save(ms, ImageFormat.Png);
猜你喜欢
  • 2013-08-15
  • 2013-02-12
  • 2010-10-28
  • 1970-01-01
  • 2018-05-26
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多