MVC图像 - 在选项卡中显示而不是下载到文件

时间:2018-02-14 18:52:13

标签: asp.net-mvc razor png filestream

我有以下控制器方法从web api获取PNG。

        public async Task<ActionResult> RealTimeUpdate(string fundName)
        {
        string docPath = ConfigurationManager.AppSettings["RealTimeUpdate"].Replace("{fundname}",fundName).ToString();
        docPath = docPath.Replace("\\\\", "\\");
        docPath = docPath.Replace("\"", "");

        string url = ServiceUrl + "api/RealTime/" + fundName;
        HttpResponseMessage response = await client.GetAsync(url);
        if (response.IsSuccessStatusCode)
        {
            var dataStream = response.Content.ReadAsStringAsync().Result;
            if (dataStream == null)
                return HttpNotFound();
            var _buffer = JsonConvert.DeserializeAnonymousType(dataStream, new { _buffer = (byte[])null })._buffer;

            // If user decides to save the file, this will help...
            //Response.AddHeader("content-disposition", "filename=" + Path.GetFileName(path));
            return File(_buffer, "application/png");
        }
        return View("Error");
    }

我称之为:

<a href="@Url.Action("RealTimeUpdate", "Documents", new { FundName = "RealTimeUpdate"})" class="btn rt-info rtBtn" target="_blank">Real Time Update</a>

正如您所看到的,我有target =“_ blank”,但是,它不是在新标签中显示图像,而是将其下载到我的文档文件夹中。如何让它显示在选项卡中?

1 个答案:

答案 0 :(得分:0)

你需要一个ImageController来渲染它。

一旦有了控制器,就可以按如下方式进行渲染:

public class ImageController{

public ActionResult ShowImage(string path) 
{

    return File(path);
}

}

在您的观点中:

<img src="@Url.Action("Render","Image", new {id =1  // or path })" />

这个答案取自https://stackoverflow.com/a/16142574/5586581