我可以创建一个简单地返回图像资产的控制器吗?

我想通过控制器路由这个逻辑,每当请求如下URL时:

www.mywebsite.com/resource/image/topbanner

控制器将查找topbanner.png并将图像直接发送回客户端。

我见过这样的例子,你必须创建一个视图-我不想使用视图。我想只用控制器来做。

这可能吗?


当前回答

更新:有比我原来的答案更好的选择。这在MVC之外工作得很好,但最好坚持使用返回图像内容的内置方法。见赞成投票的答案。

你当然可以。试试下面这些步骤:

将映像从磁盘加载到字节数组中 缓存图像,如果您希望对图像有更多的请求,并且不需要磁盘I/O(我的示例在下面没有缓存它) 通过响应改变mime类型。ContentType 响应。写出图像字节数组

下面是一些示例代码:

string pathToFile = @"C:\Documents and Settings\some_path.jpg";
byte[] imageData = File.ReadAllBytes(pathToFile);
Response.ContentType = "image/jpg";
Response.BinaryWrite(imageData);

希望有帮助!

其他回答

我有两个选择:

1)实现你自己的IViewEngine,设置控制器的ViewEngine属性,你正在使用你的ImageViewEngine在你想要的“image”方法。

2)使用视图:-)。只需改变内容类型等。

你可以使用文件返回一个文件,如视图,内容等

 public ActionResult PrintDocInfo(string Attachment)
            {
                string test = Attachment;
                if (test != string.Empty || test != "" || test != null)
                {
                    string filename = Attachment.Split('\\').Last();
                    string filepath = Attachment;
                    byte[] filedata = System.IO.File.ReadAllBytes(Attachment);
                    string contentType = MimeMapping.GetMimeMapping(Attachment);

                    System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = filename,
                        Inline = true,
                    };

                    Response.AppendHeader("Content-Disposition", cd.ToString());

                    return File(filedata, contentType);          
                }
                else { return Content("<h3> Patient Clinical Document Not Uploaded</h3>"); }

            }

查看ContentResult。这将返回一个字符串,但可用于创建您自己的类binaryresult。

你可以使用HttpContext。响应并直接将内容写入它(WriteFile()可能为您工作),然后从您的动作返回ContentResult而不是ActionResult。

免责声明:我没有尝试过这个,这是基于查看可用的api。: -)

下面的代码使用System.Drawing.Bitmap来加载图像。

using System.Drawing;
using System.Drawing.Imaging;

public IActionResult Get()
{
    string filename = "Image/test.jpg";
    var bitmap = new Bitmap(filename);

    var ms = new System.IO.MemoryStream();
    bitmap.Save(ms, ImageFormat.Jpeg);
    ms.Position = 0;
    return new FileStreamResult(ms, "image/jpeg");
}