2013-12-11 30 views
0

我有一個MVC Web應用程序,並試圖在頁面上顯示一個圖像(來自數據庫),但沒有成功。遵循我找到的各種例子;我有我的頁面「ImageTest.aspx」和處理「ImageViewer.ashx」用MVC顯示數據庫圖像頁面

處理程序的內容是

<%@ WebHandler Language="C#" Class="ImageHandler" %> 

using System.Web; 

namespace Decri.WebClient.Views.Tablet 
{ 
    public class ImageViewer : IHttpHandler 
    { 
     public void ProcessRequest(HttpContext context) 
     { 
      context.Response.ContentType = "image/jpeg"; 
      context.Response.WriteFile("palmtree.jpg"); 
     } 

     public bool IsReusable 
     { 
      get { return false; } 
     } 
    } 
} 

我「ImageTest」頁面包含以下(試圖獲得工作的基本功能使用數據庫)之前

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server"> 

    <h2>Image Test</h2> 

    <img src="ImageViewer.ashx?id=1" alt="Dynamic Image" /> 

</asp:Content> 

該頁面加載與「紅十字」缺失的圖像圖標,當在調試,代碼不停車時我已經在處理程序放在「的ProcessRequest」斷點。查看HTML源代碼,代碼與上面相同(添加從Site.Master中獲取的HTML)。

我們總部設在這裏下車控制器,其中在控制器中的條目一直保持簡單(沒有在控制器的處理器,這是我理解是正確的)的:

public ActionResult ImageTest() 
    { 
     return View(); 
    } 

我注意到如果我在文件夾中有一個正常的圖像並通常引用它(沒有處理程序),它不會顯示;將它移動到CONTENT \ IMAGES文件夾中,然後就可以了。試圖將處理程序複製到CONTENT \ IMAGES文件夾中,並且「沒有任何區別。

我現在有些不知所措,並希望得到任何有此問題並得到它工作的人的指導。

回答

3

試試這個:

context.Response.WriteFile(context.Server.MapPath("~/Content/Images/palmtree.jpg")); 

如果不調用MapPath處理程序將查找圖像中應用程序的bin目錄。

由於您使用的MVC框架有一個更加一致的方式(你不需要實現自己的處理程序):

public class HelloController : Controller 
{ 
    public ActionResult ShowImage(int id) 
    { 
     var fileName = "palmtree.jpg"; 
     var rawFile = LoadFile(); //Assuming, LoadFile() returns byte[] 

     return File(rawFile, MimeMapping.GetMimeMapping(fileName), fileName); 
    } 
} 

查看:

<img src="@Url.Action("ShowImage", "Hello", new { id = 1 })" alt="Dynamic Image" /> 
+0

輝煌,謝謝!簡單的答案可以是多麼美妙。 – Sean