Jared Feldman
Jared Feldman

Reputation: 23

Serve Image with IHttpHandler

I am working with a web server that is only available on our internal network. I have a need to make an image it serves available to the public via our DMZ web server. The internal system has a GUI where anyone can upload any type of image so my HttpHandler must be flexible.

The bit of code I am currently using is:

WebResponse webResponse = WebRequest.Create(imagePath).GetResponse();
using (Stream stream = webResponse.GetResponseStream())
{
    context.Response.Clear();
    context.Response.ContentType = webResponse.ContentType;
    stream.CopyTo(context.Response.OutputStream);
    context.Response.End();
}

This seems to work and it serves up images correctly on HTML pages, but when I right click in Chrome and select "Open image in new tab" I get garbled up text like this:

enter image description here

Any suggestions to make my code better or is this okay?

Thanks!

EDIT: Seems like this code snippet does exactly what it should do. The problem was with the internally hosted image itself. It Served the exact same garbled text even before running through this HttpHandler.

Upvotes: 0

Views: 394

Answers (1)

riwalk
riwalk

Reputation: 14223

Your content type header is probably not being set correctly.

Change it to context.Response.ContentType = "image/png";, but replace "png" with whatever the image time you are loading happens to be.

Upvotes: 3

Related Questions