如何在java servlet中接收canvas`toDataURL()`?

时间:2016-09-19 13:15:32

标签: javascript java ajax canvas base64

不知何故,我通过相机捕获画布图像并将其canvas.toDataURL()发送到服务器,以便服务器可以将其保存为png文件,现在我提到问题之前是我的代码:

var dataURL = canvas.toDataURL("image/png");
    formdata = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    alert(formdata);
    $.ajax({
        url: '../canvasdopost',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
        success: function(data){

        }
    });

服务器:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     Part part = request.getPart("canvasdata");
      BufferedReader br = new BufferedReader(new InputStreamReader(part.getInputStream(),
          Charset.forName("utf-8")));
      String sImg = br.readLine();
      System.out.print(sImg);
}

服务器控制台输出:

  

java.lang.IllegalStateException:由于未提供多部件配置,因此无法处理部件       在org.apache.catalina.connector.Request.parseParts(Request.java:2733)

我也尝试过:

String test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
System.out.print(test);

现在的问题是,在发送数据之前,我从未让我的服务器控制台输出我在客户端警报框中的内容。

感谢那些告诉我如何将收到的base64数据保存到实际图像文件的人

1 个答案:

答案 0 :(得分:0)

仅针对那些面临同样问题的人,

这很简单:

服务器:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    System.out.print(test);
    byte[] bImg64 = test.getBytes();
    byte[] bImg = Base64.decodeBase64(bImg64); // apache-commons-codec
    FileOutputStream fos = new FileOutputStream("D:\\img.png");
    fos.write(bImg);
    fos.close();
}

客户端:

var dataURL = canvas.toDataURL("image/png");
formdata = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
$.ajax({
    url: '../signupcanvasdopost',
    type: 'POST',
    data: formdata,
    processData: false,
    contentType: "text/html",
    success: function(data){

    }
});