开发者

Use jQuery load with a custom http handler ashx file to show a png

开发者 https://www.devze.com 2023-02-27 00:24 出处:网络
I have a custom handler (ImageHandler.ashx) that works fine when browsed to.It locates a zip file on the开发者_开发知识库 server, unzips it and saves a bitmap to the OutputStream.When I try to use jQu

I have a custom handler (ImageHandler.ashx) that works fine when browsed to. It locates a zip file on the开发者_开发知识库 server, unzips it and saves a bitmap to the OutputStream. When I try to use jQuery load using the ashx my png content comes back as encoded, garbled characters rather than displaying the image.

Bitmap convertedImg = new Bitmap(zInStream);
convertedImg.Save(context.Response.OutputStream, ImageFormat.Png);


That is because what you are requesting from the server is an image, it's not HTML code that shows an image.

Instead of using the load method, just create an image element with the URL to the handler as source:

$('#SomeElement').append($('<img/>', { src: 'ImageHandler.ashx', alt: 'An image' }));

Note: If the zip file contains a PNG image, then you don't have to unpack it to a Bitmap object and then pack it to PNG format again, you can just send the contents of the zip stream directly to the response stream.


Make sure you set the content type on your response to "image/png" like so:

context.Response.ContentType = "image/png";
Bitmap convertedImg = new Bitmap(zInStream);
convertedImg.Save(context.Response.OutputStream, ImageFormat.Png);

This ensures that the browser will treat the returned content as a PNG image instead of text/html.

Edit
Also, I recommend against doing cpu intensive decompression every time that image is loaded. It would be much faster (and better for your server) if you only unzipped it once and then referenced the unzipped version from then on.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号