1

I have been trying to save a canvas image from my HTML page to an image file in Java Servlet. I need to send the image from HTML to Java Servlet through an Ajax request. Can someone please help me out? I have already tried out the following option

Stack Overflow Question 1

Here, request.getPart("myImg") is returning null, hence this is not working. Please help me out.

I have also tried the following solution Sending content of canvas to java

The problem here is that it is giving me an exception of invalid literal/lengths set at the following line

BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes)); 

Please help!!

UPDATE:

Here is my Ajax Code:

function uploadImage() {
    var canvasServer = document.getElementById("canvasThumbResult");
    var context = canvasServer.getContext("2d");                    
    var imageDataURL = canvasServer.toDataURL('image/png');

    var xhr = new XMLHttpRequest();
    xhr.open("POST", trinityCvaServicesUrl+"common/uploadImage", true);
    var boundary = Math.random().toString().substr(2);
    xhr.setRequestHeader("content-type", 
        "multipart/form-data; charset=utf-8; boundary=" + boundary);
    var multipart = "--" + boundary + "\r\n" +
        "Content-Disposition: form-data; name=myImg\r\n" +
        "Content-type: image/png\r\n\r\n" +
        imageDataURL + "\r\n" +
        "--" + boundary + "--\r\n";
    xhr.send(multipart);    
    /*xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("imgData="+imageDataURL);*/
}

And here is my Java Code:

FileOutputStream fos = null;
        try {
            Part part = req.getPart("myImg");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    part.getInputStream(), Charset.forName("utf-8")));

            /*String imgData = request.getParameter("imgData");
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new ByteArrayInputStream(
                            imgData.getBytes(StandardCharsets.UTF_8)),
                    Charset.forName("utf-8")));*/

            String sImg = br.readLine();
            sImg = sImg.substring("data:image/png;base64,".length());
            byte[] bImg64 = sImg.getBytes();
            byte[] bImg = Base64.decodeBase64(bImg64); 
            fos = new FileOutputStream(ReloadableProps.getProperty("local.image.save.path")+"img.png");
            fos.write(bImg);

            /*String imgData = req.getParameter("imgData");
            String img64 = imgData.replaceAll("data:image/png;base64,", "");
            byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64 );
            BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));    
            File outputfile = new File(ReloadableProps.getProperty("local.image.save.path")+"img.png");
            ImageIO.write(bfi , "png", outputfile);
            bfi.flush();*/
        } catch (Exception e) {
            e.printStackTrace();
            String loggerMessage = "Upload image failed : ";
            CVAException.printException(loggerMessage + e.getMessage());
        } finally {
            if(fos != null) {
                fos.close();
            }
        }
4
  • Instead of linking to different questions hoping we can guess how you patched their code together, why not post your Ajax code? Commented Jun 10, 2014 at 22:01
  • Thanks for your response. I have posted the ajax and java code in my question. Please help.. Commented Jun 11, 2014 at 6:50
  • You should post the stack trace as well, and indicate what line the top of the stack trace corresponds to in your source. Or otherwise indicate in what way the above doesn't work. Commented Jun 11, 2014 at 11:49
  • In the java code above, the req.getPart("myImg"); object is coming as null. Hence the BufferedReader code fails due to NullPointerException. Please let me know if you need more information. Commented Jun 11, 2014 at 12:11

1 Answer 1

3

I have managed to save the image somehow. Not sure if that is an efficient way of doing this. Please comment if you feel this might not be an efficient way of doing this. Appreciate your feedback.

My JavaScript code:

    var canvasServer = document.getElementById("canvasThumbResult");
    var context = canvasServer.getContext("2d");                    
    var imageDataURL = canvasServer.toDataURL('image/png');
    var ajax = new XMLHttpRequest();
    ajax.open("POST",trinityCvaServicesUrl+"common/uploadImage",false);
    ajax.setRequestHeader("Content-Type", "application/upload");
    ajax.send(imageDataURL);

My Java Code:

        InputStream in = null;
        FileOutputStream fos = null;
        try {
            HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(req);
            InputStream is = wrappedRequest.getInputStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            String imageString = writer.toString();
            imageString = imageString.substring("data:image/png;base64,"
                    .length());
            byte[] contentData = imageString.getBytes();
            byte[] decodedData = Base64.decodeBase64(contentData);
            String imgName = ReloadableProps
                    .getProperty("local.image.save.path")
                    + String.valueOf(System.currentTimeMillis()) + ".png";
            fos = new FileOutputStream(imgName);
            fos.write(decodedData);
        } catch (Exception e) {
            e.printStackTrace();
            String loggerMessage = "Upload image failed : ";
            CVAException.printException(loggerMessage + e.getMessage());
        } finally {
            if (in != null) {
                in.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

I was stuck in js, changing content type worked for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.