将图像作为FileContentResult .net返回

时间:2014-11-29 22:22:52

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

我基本上试图从服务器上的方法将图像返回给客户端。它适用于除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" })" />

任何帮助都非常感激。

1 个答案:

答案 0 :(得分: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”;)