使用 jQuery load 和自定义 http 处理程序 ashx 文件来显示 png

发布于 2024-11-02 06:32:38 字数 286 浏览 6 评论 0原文

我有一个自定义处理程序(ImageHandler.ashx),在浏览时可以正常工作。它在服务器上找到一个 zip 文件,将其解压缩并将位图保存到 OutputStream。当我尝试使用 ashx 进行 jQuery 加载时,我的 png 内容会以编码的乱码形式返回,而不是显示图像。

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

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

少女七分熟 2024-11-09 06:32:38

这是因为您从服务器请求的是图像,而不是显示图像的 HTML 代码。

无需使用 load 方法,只需创建一个图像元素,并将处理程序的 URL 作为源:

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

注意:如果 zip 文件包含 PNG 图像,则无需将其解压为Bitmap 对象,然后再次将其打包为 PNG 格式,您可以将 zip 流的内容直接发送到响应流。

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.

旧瑾黎汐 2024-11-09 06:32:38

确保将响应中的内容类型设置为 "image/png",如下所示:

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

这可确保浏览器将返回的内容视为 PNG 图像而不是 text/html。

编辑
另外,我建议不要在每次加载图像时都进行 CPU 密集型解压缩。如果您只解压缩一次,然后从那时起引用解压缩的版本,那么速度会快得多(并且对您的服务器更好)。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文