下载动态生成的图像,而不是在浏览器中显示

时间:2015-11-10 00:06:08

标签: c# asp.net-mvc fileresult

我创建了一个将URL(HTML)的内容转换为图像(JPG)的Action,然后将其返回给我,然而,浏览器正在下载它而不是显示。

图像是动态生成的,我没有在硬盘中生成。

我的代码如下:

[AllowAnonymous]
public FileResult URLToImage(string url)
{
    // In some cases you might want to pull completely different URL that is not related to your application.
    // You can do that by specifying full URL.
    UrlAsImage urlImg = new UrlAsImage(url)
    {
        FileName = Guid.NewGuid().ToString() + ".jpg",
        PageHeight = 630,
        PageWidth = 1200
    };
    return File(urlImg.BuildFile(this.ControllerContext), "image/jpg", urlImg.FileName);
}

我需要做什么才能在浏览器中显示它而不是下载它?

1 个答案:

答案 0 :(得分:4)

返回FileResult并将标题中的Content-Disposition设置为内嵌

[AllowAnonymous]
public FileResult URLToImage(string url)
{
    // In some cases you might want to pull completely different URL that is not related to your application.
    // You can do that by specifying full URL.
    UrlAsImage urlImg = new UrlAsImage(url)
    {
        FileName = Guid.NewGuid().ToString() + ".jpg",
        PageHeight = 630,
        PageWidth = 1200
    };
    Response.AddHeader("Content-Disposition", "inline; filename="+urlImg.FileName);
    return File(urlImg.BuildFile(this.ControllerContext), "image/jpg");
}