Santosh Sahu
Santosh Sahu

Reputation: 219

Access Local Image through .ashx in asp.net

I am using an ashx file to retrieve an image from the database. If it is not available in Database it'll show another image which is inside my project folder. But I am not able to access the local image. Can any body help me or suggest something?

My Code:

public void ProcessRequest (HttpContext context) 
{
    context.Response.ContentType = "text/plain";
    string Value = (string)context.Session["UserID"];
    Stream strm = ShowEmpImage(Value);
    if (strm == null)
    {
        byte[] imageBytes = File.ReadAllBytes("~/images/photo_not_available.png" + context.Request["image"]);
        context.Response.ContentType = "image/png";
        context.Response.BinaryWrite(imageBytes);          
    }
    else
    {
        byte[] buffer = new byte[4096];
        int byteSeq = strm.Read(buffer, 0, 4096);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
        }
    }   
   //context.Response.BinaryWrite(buffer);
}

ThnnQ

Upvotes: 0

Views: 1794

Answers (2)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

Could you use the HttpResponse.TransmitFile method

Response.TransmitFile(context.Request.MapPath("~/images/photo_not_available.png"));

Upvotes: 1

Aristos
Aristos

Reputation: 66641

For sure you have a bug here, you add on the image file name, one more variable - this is for sure make a non existing file.

byte[] imageBytes = 
File.ReadAllBytes("~/images/photo_not_available.png" + context.Request["image"]);

a Second bug here is that you do not make MapPath of your ~

    byte[] imageBytes = File.ReadAllBytes(
content.Request.MapPath("~/images/photo_not_available.png"));

Or you can call it as @zapthedingbat suggest.

One more issue, you start with

 context.Response.ContentType = "text/plain";

and then you change it to

context.Response.ContentType = "image/png";

Upvotes: 2

Related Questions