I want to upload a html canvas to a java servlet and return the canvas data as a png image. My problem is that the response from the servlet is not correct and therefor not rendered as an image. Saving the file on disk works fine though.
What am I doing wrong? Do I need to set any more headers? Content-length?
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
BufferedImage bfi = null;
OutputStream out = null;
PrintWriter htmlOut = null;
try{
response.setContentType("image/png");
String img64 = (String) request.getParameter("base64image");
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64 );
bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
out = response.getOutputStream();
ImageIO.write(bfi, "png", out);
//Save on disk
File outputfile = new File("webapps/saved.png");
ImageIO.write(bfi , "png", outputfile);
}catch(Exception e){
//ERROR HANDLING
}
finally{
if(bfi != null){
bfi.flush();
}
if(out != null){
out.flush();
out.close();;
}
if(htmlOut != null){
htmlOut.close();
}
}
}