1

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

}
gusjap
  • 2,397
  • 5
  • 24
  • 38

2 Answers2

0

Maybe I am blind but I just cannot see you setting the Content-Length header on the response object.

Rafal G.
  • 4,252
  • 1
  • 25
  • 41
  • I tried setting the Content-Length to "decodedBytes.length" but I still couldn't get it to work. – gusjap Oct 28 '14 at 18:15
0

I had the same problem but only in IE with the error message:

An existing connection was forcibly closed by the remote host

The following post helped me: https://stackoverflow.com/a/8623747/1064057

I had to set the mime type and the content length.

String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file);
if (contentType == null) {
   log.warn("Cannot get mime type of file" + file.getAbsolutePath());
} else {
   response.setContentType(contentType);
}
response.setContentLength((int)file.length());

Perhaps this helps in another case or someone else.
Kind regards
Aurel

Community
  • 1
  • 1
Aurelius Baier
  • 121
  • 1
  • 6