简体   繁体   中英

Trouble converting simple PNG download script from PHP to Java

I'm trying to download a PNG image from a Flash application using a Java servlet. I was using this PHP script, which worked perfectly, but need to switch to a Java servlet instead.

PHP:

<?php
   header('Content-Type: image/png');
   header("Content-Disposition: attachment; filename=out.png");
   echo base64_decode($_POST["image"]);
?>

And my Java code:

String image = getRequest().getParameter("image");
String decodedImage = new String(Base64.decode(image));
HttpServletResponse resp = op.getResponse();
resp.setContentType("image/png");
resp.addHeader("Content-Disposition", "attachment;filename=out.png");
resp.getWriter().write(image);
resp.getWriter().flush(); 

I've tried two separate Base64 decoder classes with the same results. The decoded base64 is written as a response but the PNG is corrupt. One difference I can see in the HTTP response header is that the Servlet uses "image/png; charset=UTF-8" while the PHP script just uses "image/png".

Thanks for the help!

FIX - thanks Ignacio Vazquez-Abrams!

resp.setContentType("image/png");
resp.addHeader("Content-Disposition", "attachment;filename=out.png");
resp.getOutputStream().write(image);
resp.getOutputStream().close();

Use .getOutputStream() , not .getWriter() . You need to send it as binary data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM