Search code examples
asp.netasp.net-mvcasp.net-mvc-5httphandler

Image Handler not Loading Image


I am using Image handler to resize image. But it is not loading image.

View :

 <img src="ImageHandler.ashx?file=~/Images/Releases/koala.jpg" style="width:100px; height:100px;" />

Image Handler code.enter image description here Sorry I was not able to add the whole image handler code here so added as image. What I am missing here. Please suggest.


Solution

  • I found two issues.

    1. QueryString value in the request URL should be just filename - ImageHandler.ashx?file=koala.jpg

      <img src="ImageHandler.ashx?file=koala.jpg" style="width:100px; height:100px;" />

    2. QueryString name should be file instead of photo_url.

    Please make sure the following code works before resizing it.

    public class ImageHandler : IHttpHandler
    {    
        public void ProcessRequest(HttpContext context)
        {
            string fileName = context.Request.QueryString["file"];
            string filePath = context.Server.MapPath("~/Images/Releases/" + fileName);
    
            context.Response.AddHeader("content-disposition", 
                 string.Format("attachment; filename={0}", fileName));
    
            if (File.Exists(filePath))
            {
                byte[] bytes = File.ReadAllBytes(filePath);
                context.Response.BinaryWrite(bytes);
            }
            else
            {
                throw new HttpException(404, "Invalid photo name.");
            }
        }
    
        public bool IsReusable { get { return false; } }
    }