3

我知道已经有很多关于这个的 StackOverflow 问题,但是我已经搜索了尽可能多的东西并且还没有让我的代码工作,所以我终于发布了我自己的问题。

我的目标是将<canvas>网页中 HTML5 上的图像保存到服务器上的文件中。我希望使用 Java servlet 来实现这一点。

我的 JavaScript 像这样抓取画布图像数据:

var canvas = document.getElementById("screenshotCanvas");
var context = canvas.getContext("2d");                    
var imageDataURL = canvas.toDataURL('image/png');
// I'm not if I need to do this, I've tried several different ways to no avail
//imageDataURL = imageDataURL.replace("image/png", "image/octet-stream");
//imageDataURL = imageDataURL.replace(/^data:image\/(png|jpeg);base64,/,"");

$.ajax({
    url: screenshotCreateUrl,
    type: "POST",
    data: { imgBase64: imageDataURL },
    error: function(jqXHR, textStatus, errorThrown) {
        // Handle errors
    },
    success: function(data, textStatus, jqXHR) {
        // Do some stuff
    }
});

我的 Java servlet 尝试像这样保存图像:

try {
    HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
    HttpServletRequestWrapper requestWithWrapper = (HttpServletRequestWrapper) wrappedRequest.getRequest();
    byte[] contentData = requestWithWrapper.getContentData();
    byte[] decodedData = Base64.decodeBase64(contentData);          
    FileOutputStream fos = new FileOutputStream("testOutput.png");
    fos.write(decodedData);
    fos.close();
} catch(Exception e) {
    // Handle exceptions
}

servlet 成功写出一个图像文件,但它没有正确打开,并且其中不包含所有图像数据。我的 Javascript 成功抓取了<canvas>图像数据,如下所示:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAgAElEQVR4nJTa51NcaZ7ge+QBIZBAwgoEkvDeJt577733njRk4r3PhDRAJkkmiTdCXqWqUlVXtZl209OzvWN27t17/5rvvoCu7t6ZmN158YnfcyJOnIjz4vnGEyeOWdRmAP+RaI3fT2I0PiTtBJF9KKD8TTKVb5IpPosl+zCMdFMgKQY/otTPCFl3IljhSPiWB5E7XkToPAnVexNq8CVyP5Cwg0CCDwII2vfHx+TDC6MXz3df8mznGc7bTthu2PJwxRrrufvcnzbn4bQFjnNWuK3a4r3hQrDmBSGbLwlRvyR0w5OQ9ZeErHsRsuFLyIYvQeu+BCh88Zf74K/wxU8ZgL8qEH9VEAHq0L8RqAkjeCuCsO1IwrVRhGujCNNdCdVFEayNJEQXdUUfTYg+mmC9AH99BL47YfjuhOK7G4KvIRhfQzDee4F47QXibQrCe98f730/vPf98N3zw9/kT+B+IG . . . [and so on]

有什么想法我在这里想念的吗?我觉得我犯了一些我无法发现的小错误。

4

2 回答 2

3

通过使用 multipart/form-data 内容类型,有相同的任务并且能够使其工作(没有 jQuery 并在 maclema 的回复的帮助下):

var xhr = new XMLHttpRequest();
xhr.open("post", "AddressOfYourServlet", false);
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" +
    canvas.toDataURL("image/png") + "\r\n" +
    "--" + boundary + "--\r\n";
xhr.send(multipart);

要异步进行,或者如果您有更多部分要发送(例如多个图像),或者如果您想处理响应,请参阅如何通过 ajax(无 jquery)发送 multipart/form-data 表单内容?

您的 servlet 的doPost方法如下所示:

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {
  Part part = request.getPart("myImg");
  BufferedReader br = new BufferedReader(new InputStreamReader(part.getInputStream(),
      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); // apache-commons-codec
  FileOutputStream fos = new FileOutputStream("img.png");
  fos.write(bImg);
}

希望这可以帮助。

于 2013-12-30T18:00:32.250 回答
1

您想要获取 post 参数而不是请求的内容数据。同样,您还需要剥离编码信息。

尝试这个:

try {
    HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(request);
    HttpServletRequestWrapper requestWithWrapper = (HttpServletRequestWrapper) wrappedRequest.getRequest();
    String imageString = wrappedRequest.getParameter("imgBase64");
    imageString = imageString.substring("data:image/png;base64,".length);
    byte[] contentData = imageString.getBytes();
    byte[] decodedData = Base64.decodeBase64( contentData );          
    FileOutputStream fos = new FileOutputStream("testOutput.png");
    fos.write(decodedData);
    fos.close();
} catch(Exception e) {
    // Handle exceptions
    e.printStackTrace();
}
于 2013-06-18T22:29:16.827 回答