如何使用ajax将canvas png图像发送到java servlet?

时间:2017-05-12 14:53:38

标签: javascript java ajax servlets canvas

我正在尝试使用ajax将画布PNG发送到java servlet。 这是我的javascript代码:

function sendToServer(image){   
$.ajax({
    type: "POST",
    url: "SaveAnnotation",
    data: {
        annotationImage: image
        },
    success: function(msg)
    {                       
            alert(msg);
    },
    error: function()
    {
        alert("Error connecting to server!");
    }
}); 
}

function save() {
var dataURL = canvas.toDataURL();
sendToServer(dataURL);
}

java servlet doPost():

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/plain");      
    try{
        String img64 = request.getParameter("annotationImage");
        byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64);
        BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));    
        File outputfile = new File("saved_annotations/saved.png");
        ImageIO.write(bfi , "png", outputfile);
        bfi.flush();   
        out.print("Success!");
    }catch(IOException e){  
          out.print(e.getMessage());
    }
}

问题是getParameter("annotationImage")返回null,我无法理解原因:使用浏览器调试器我可以看到annotationImage及其在请求参数之间的值,所以我肯定它不是null,但由于某种原因,Java Servlet不接收该参数。

1 个答案:

答案 0 :(得分:0)

我发现了它无效的原因。 为了避免解析JSON,我将数据发送到服务器而不设置任何参数,编写data: image而不是JSON格式data: {annotationImage: image}以避免在servlet中进行JSON解析。

在java servlet中,我得到整个请求体,删除内容类型声明,最后解码并保存图像。这是代码:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");

    StringBuffer jb = new StringBuffer();
    String line = null;
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
        jb.append(line);

    String img64 = jb.toString();   
    //check if the image is really a base64 png, maybe a bit hard-coded
    if(img64 != null && img64.startsWith("data:image/png;base64,")){
        //Remove Content-type declaration
        img64 = img64.substring(img64.indexOf(',') + 1);            
    }else{
        response.setStatus(403);
        out.print("Formato immagine non corretto!");
        return;
    }   
    try{
        InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(img64.getBytes()));  
        BufferedImage bfi = ImageIO.read(stream);
        String path = getServletConfig().getServletContext().getRealPath("saved_annotations/saved.png");
        File outputfile = new File(path);
        outputfile.createNewFile();
        ImageIO.write(bfi , "png", outputfile);
        bfi.flush();
        response.setStatus(200);
        out.print("L'immagine e' stata salvata con successo!");         
    }catch(IOException e){  
        e.printStackTrace();
        response.setStatus(500);
        out.print("Errore durante il salvataggio dell'immagine: " + e.getMessage());      
    }
}