Search code examples
asp.netwebformsashx

Writing a image to ASHX


I am editing an old .NET 3.5 site and need it to download an image, then provide it to a request. Basically a pass-though.

The data gets sent as the correct size, but the image does not appear.

public class AppImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        var url = "http://static.idolator.com/uploads/2015/10/adele-hello.jpg";

        HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(url);
        WebResponse imageResponse = imageRequest.GetResponse();
        Stream responseStream = imageResponse.GetResponseStream();

        byte[] buffer = new byte[imageResponse.ContentLength];
        int read;
        Stream output = new MemoryStream();
        while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
        responseStream.Close();

        HttpResponse r = context.Response;
        r.ContentType = "image/jpg";
        r.BinaryWrite(buffer);

    }

Solution

  • I wasn't reading the full stream.

    I used this to get the full byte array and then it works

    public static byte[] ReadFully(Stream input)
    {
     byte[] buffer = new byte[16*1024];
     using (MemoryStream ms = new MemoryStream())
     {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
     }
    }