views:

1390

answers:

2

I have an ashx handler:

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

using System;
using System.Web;

public class Thumbnail : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string imagePath = context.Request.QueryString["image"];

        // split the string on periods and read the last element, this is to ensure we have
        // the right ContentType if the file is named something like "image1.jpg.png"
        string[] imageArray = imagePath.Split('.');

        if (imageArray.Length <= 1)
        {
            throw new HttpException(404, "Invalid photo name.");
        }
        else
        {
            context.Response.ContentType = "image/" + imageArray[imageArray.Length - 1];
            context.Response.Write(imagePath);
        }
    }

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

For now all this handler does is get an image and return it. In my aspx page, I have this line:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

And the C# code behind it is:

Image1.ImageUrl = "Thumbnail.ashx?image=../Files/random guid string/test.jpg";

When I view the web page, the images are not showing and the HTML shows exactly what I typed:

<img class="thumbnail" src="Thumbnail.ashx?image=../Files%5Crandom guid string%5Cimages%5Ctest.jpg" style="border-width:0px;" />

Can someone tell me why this isn't working? Unfortunately I only started working with ASP.NET yesterday and I have no idea how it works, so please keep the explanations simple if possible, thanks.

+1  A: 

You are printing out the path to the image instead of the actual image contents. Use

context.Response.WriteFile(context.Server.MapPath(imagePath));

method instead.

Make sure you restrict the path to some safe location. Otherwise, you might introduce security vulnerabilities as users would be able to see contents of any file on the server.

Mehrdad Afshari
Actually, what I want is only the path because I want to set the `img src`. Later on I plan to have the HttpHandler generate a thumbnail, then return the path to it.
That's not what a HTTP handler does. The browser just treats the handler as an image file. It can't change the original HTML response of the page.
Mehrdad Afshari
A: 

Hello, I'm the original poster and I finally figured out the problem. All I had to do was change:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

to:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" imageurl='<%# "~/Thumbnail.ashx?image=" + Utilities.ToURLEncoding("~\\Files" + DataBinder.Eval(Container.DataItem, "file_path")) %>' />

Punctuation needs to be changed to its HTML equivalent, so backslashes become %5C, etc..., or else it won't work.

Oh, I forgot to mention, this is in a DataList. Using Image1.ImageUrl = "Thumbnail.ashx?image=blahblah"; outside of a DataList works perfectly fine, strangely.

Daniel T.