【问题标题】:Return image from Controller从控制器返回图像
【发布时间】:2017-01-27 08:31:31
【问题描述】:

控制器:

public ActionResult Beacon(string value)
{
    var dir = Server.MapPath("/Content/Images/Sprites/");
    var path = Path.Combine(dir, "logo.png");
    return base.File(path, "image/png");

}

生成的 HTML:

<img style="-webkit-user-select: none" src="http://localhost:38315/Beacon/999">

但是图像不显示。在 Chrome 中,它是一个带有灰色边框的小框,在 MS Edge 中,有一个带有“X”的框,我认为它是“找不到文件”图像。

我尝试返回不同的图像(以确保第一个没有损坏),几种内容类型但没有任何运气。

我确定我尝试过的不同文件存在。

我读了这篇文章:ASP.Net MVC - Img Src Server Path

我试过这个:

return File("~/images/beacon.png", "image/png");

我尝试返回 Base64 字符串,但没有成功。

当我运行此代码时,它表明该文件确实存在:

var dir = Server.MapPath("/images");
var path = Path.Combine(dir, "beacon.png");
var res = System.IO.File.Exists(path);
return base.File(path, "image/png");

如何通过控制器返回简单的图像?

* Willy David Jr 建议 *

public ActionResult Beacon(string value) {

var path =  Server.MapPath(Url.Content("~/Content/Images/Sprites/")) + "logo.png";
var theFile = new FileInfo(path);

if (theFile.Exists) {
    return File(System.IO.File.ReadAllBytes(path), "image/png");
    //or return base.File(path, "image/png");
}
    return this.HttpNotFound();                
}

【问题讨论】:

  • 调试时是否命中动作?检查给定图像的路径是否映射到动作。另外,在路径上执行System.IO.File.Exsits(path) 并确保派生路径在那里。您生成的路径可能是错误的。
  • @Nkosi 更新了答案。 “res”是真的,即它似乎存在。

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


【解决方案1】:

尝试以下方法,看看它是否适用于您的情况。

public ActionResult Beacon(string value) {
    var dir = Server.MapPath("/Content/Images/Sprites/");
    var path = Path.Combine(dir, "logo.png");
    var theFile = new FileInfo(path);
    if (theFile.Exists) {
        return File(System.IO.File.ReadAllBytes(path), "image/png");
    }
    return this.HttpNotFound();                
}

【讨论】:

  • 感谢您的评论。它返回错误图像,即“theFile.Exists”通过。 =/
  • 是的,先生,我是。它声明文件确实存在并给出了一个确实存在的路径。
【解决方案2】:

尝试这样做:

public ActionResult Beacon(string value) {

var path =  Server.MapPath(Url.Content("~/Content/Images/Sprites/")) + "logo.png";
var theFile = new FileInfo(path);

if (theFile.Exists) {
    return File(System.IO.File.ReadAllBytes(path), "image/png");
    //or return base.File(path, "image/png");
}
    return this.HttpNotFound();                
}

【讨论】:

  • 感谢您的建议,但很遗憾没有。我编辑了我的问题并使用您的解决方案添加了一些屏幕截图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2014-01-26
  • 2016-02-29
  • 2016-11-19
  • 2020-02-18
  • 2015-10-15
  • 2013-01-28
相关资源
最近更新 更多