【发布时间】:2012-02-13 18:40:00
【问题描述】:
如何创建一个名为GetMyImage() 的控制器方法,它返回一个图像作为响应(即图像本身的内容)?
我想过将返回类型从 ActionResult 更改为 string,但这似乎没有按预期工作。
【问题讨论】:
-
你是什么意思'返回图像'当时是什么类型?
标签: c# asp.net-mvc
如何创建一个名为GetMyImage() 的控制器方法,它返回一个图像作为响应(即图像本身的内容)?
我想过将返回类型从 ActionResult 更改为 string,但这似乎没有按预期工作。
【问题讨论】:
标签: c# asp.net-mvc
使用控制器的File方法返回FilePathResult
public ActionResult GetMyImage(string ImageID)
{
// Construct absolute image path
var imagePath = "whatever";
return base.File(imagePath, "image/jpg");
}
有几个overloads of File 方法。使用最适合您的情况的任何东西。例如,如果您想发送 Content-Disposition 标头以便用户获取 SaveAs 对话框而不是在浏览器中看到图像,您将传入第三个参数 string fileDownloadName。
【讨论】:
查看FileResult 课程。例如用法见here。
【讨论】:
你可以像这样使用FileContentResult:
byte[] imageData = GetImage(...); // or whatever
return File(imageData, "image/jpeg");
【讨论】:
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");
}
【讨论】:
只需根据您的情况尝试其中一种(复制自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");
}
【讨论】: