C# ASP .NET MVC - 有在响应中返回图像的控制器方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9265995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP .NET MVC - Have a controller method that returns an image in the response?
提问by Mathias Lykkegaard Lorenzen
How can I make a controller method called GetMyImage()which returns an image as the response (that is, the content of the image itself)?
我怎样才能调用一个控制器方法GetMyImage()来返回一个图像作为响应(即图像本身的内容)?
I thought of changing the return type from ActionResultto string, but that doesn't seem to work as expected.
我想将返回类型从ActionResultto更改为string,但这似乎没有按预期工作。
采纳答案by amit_g
Return FilePathResultusing Filemethod of controller
使用控制器的File方法返回FilePathResult
public ActionResult GetMyImage(string ImageID)
{
// Construct absolute image path
var imagePath = "whatever";
return base.File(imagePath, "image/jpg");
}
There are several overloads of Filemethod. Use whatever is most appropriate for your situation. For example if you wanted to send Content-Disposition header so that the user gets the SaveAs dialog instead of seeing the image in the browser you would pass in the third parameter string fileDownloadName.
File方法有几个重载。使用最适合您情况的方法。例如,如果您想发送 Content-Disposition 标头,以便用户获得 SaveAs 对话框而不是在浏览器中看到图像,您将传入第三个参数string fileDownloadName。
回答by Nate
Check out the FileResultclass. For example usage see here.
查看FileResult类。例如用法见这里。
回答by naspinski
Simply try one of these depending on your situation (copied from here):
只需根据您的情况尝试其中之一(从此处复制):
public ActionResult Image(string id)
{
var dir = Server.MapPath("/Images");
var path = Path.Combine(dir, id + ".jpg");
return base.File(path, "image/jpeg");
}
[HttpGet]
public FileResult Show(int customerId, string imageName)
{
var path = string.Concat(ConfigData.ImagesDirectory, customerId, @"\", imageName);
return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
回答by kprobst
You can use FileContentResultlike this:
你可以这样使用FileContentResult:
byte[] imageData = GetImage(...); // or whatever
return File(imageData, "image/jpeg");
回答by Shyju
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public ActionResult Thumbnail()
{
string imageFile = System.Web.HttpContext.Current.Server.MapPath("~/Content/tempimg/sti1.jpg");
var srcImage = Image.FromFile(imageFile);
var stream = new MemoryStream();
srcImage.Save(stream , ImageFormat.Png);
return File(stream.ToArray(), "image/png");
}

