保存HTML5&LT;画布&GT;图片瓦特/的Java Servlet [英] Saving HTML5 <canvas> Image w/ Java Servlet
问题描述
我知道有很多关于这个StackOverflow的问题了,但我已经通过尽可能多的搜索,我能找到的和还没有得到我的code的工作,所以我终于发布我自己的问题。
我的目标是保存图像是在一个HTML5 &LT;画布&GT;
在我的网页,我的服务器上的文件。我希望这个使用Java servlet来完成的。
我JavasScript抓住画布图像数据是这样的:
VAR帆布=的document.getElementById(screenshotCanvas);
VAR上下文= canvas.getContext(2D);
VAR imageDataURL = canvas.toDataURL('图像/ PNG);
//我不是,如果我要做到这一点,我已经尝试了几种不同的方法都无济于事
// imageDataURL = imageDataURL.replace(图像/ PNG,图像/八位字节流);
// imageDataURL = imageDataURL.replace(/ ^数据:影像\ /(PNG | JPEG)的base64,/,);
$阿贾克斯({
网址:screenshotCreateUrl,
键入:POST,
数据:{imgBase64:imageDataURL},
错误:函数(jqXHR,textStatus,errorThrown){
//处理错误
},
成功:功能(数据,textStatus,jqXHR){
//做一些东西
}
});
我的Java servlet尝试保存图像,像这样:
尝试{
了HttpServletRequestWrapper wrappedRequest =新了HttpServletRequestWrapper(要求);
了HttpServletRequestWrapper requestWithWrapper =(了HttpServletRequestWrapper)wrappedRequest.getRequest();
byte []的contentData内容= requestWithWrapper.getContentData();
byte []的德codedData = Base64.de codeBase64(contentData内容);
FileOutputStream中FOS =新的FileOutputStream(testOutput.png);
fos.write(德codedData);
fos.close();
}赶上(例外五){
//处理异常
}
该servlet成功写出一个图像文件,但它不正常打开,并且不包含在它的所有的图像数据。我的javascript成功地抓住了&LT;画布&GT;
的图像数据,这看起来是这样的:
任何想法,我在这里缺少什么?我觉得我做了一些微小的失误,我只是不能当场。
有相同的任务,并能使其工作(不包括jQuery和与maclema答复的帮助下),通过使用多/ form-data的内容类型:
VAR XHR =新XMLHtt prequest();
xhr.open(后,AddressOfYourServlet,假);
。VAR边界=的Math.random()的toString()SUBSTR(2);
xhr.setRequestHeader(内容类型,
的multipart / form-data的;字符集= UTF-8;边界=+界);
VAR多部分= - +边界+\ r \ N+
内容处置:表格数据;名称= myImg \ r \ N+
内容类型:image / PNG \ r \ñ\ r \ N+
canvas.toDataURL(图像/ PNG)+\ r \ N+
- +边界+ - \ r \ N的;
xhr.send(多部分);
要进入异步或者如果你有更多的零部件发送(如多张图片),或者如果你想与应对工作,请参见如何通过AJAX发送的multipart / form-data的形式的内容(不jQuery的)?
您的servlet的的doPost 方式看起来是这样的:
保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)
抛出了ServletException,IOException异常{
部件部件= request.getPart(myImg);
的BufferedReader BR =新的BufferedReader(新的InputStreamReader(part.getInputStream()
Charset.forName(UTF-8)));
串SIMG = br.readLine();
SIMG = sImg.substring(数据:图像/ PNG;的base64,长度());
byte []的bImg64 = sImg.getBytes();
byte []的bImg = Base64.de codeBase64(bImg64); // Apache的commons- codeC
FileOutputStream中FOS =新的FileOutputStream(img.png);
fos.write(bImg);
}
希望这有助于。
I know there are a lot of StackOverflow questions about this already, but I've searched through as many as I could find and have yet to get my code working, so I am finally posting my own question.
My goal is to save an image that is on an HTML5 <canvas>
in my webpage to a file on my server. I was hoping to accomplish this using a Java servlet.
My JavasScript grabs the canvas image data like this:
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
}
});
My Java servlet tries to save the image like so:
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
}
The servlet successfully writes out an image file, but it does not open properly and does not contain all the image data in it. My Javascript successfully grabs the <canvas>
image data, which looks like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAgAElEQVR4nJTa51NcaZ7ge+QBIZBAwgoEkvDeJt577733njRk4r3PhDRAJkkmiTdCXqWqUlVXtZl209OzvWN27t17/5rvvoCu7t6ZmN158YnfcyJOnIjz4vnGEyeOWdRmAP+RaI3fT2I0PiTtBJF9KKD8TTKVb5IpPosl+zCMdFMgKQY/otTPCFl3IljhSPiWB5E7XkToPAnVexNq8CVyP5Cwg0CCDwII2vfHx+TDC6MXz3df8mznGc7bTthu2PJwxRrrufvcnzbn4bQFjnNWuK3a4r3hQrDmBSGbLwlRvyR0w5OQ9ZeErHsRsuFLyIYvQeu+BCh88Zf74K/wxU8ZgL8qEH9VEAHq0L8RqAkjeCuCsO1IwrVRhGujCNNdCdVFEayNJEQXdUUfTYg+mmC9AH99BL47YfjuhOK7G4KvIRhfQzDee4F47QXibQrCe98f730/vPf98N3zw9/kT+B+IG . . . [and so on]
Any ideas what I am missing here? I feel like i am making some tiny mistake that I just can't spot.
Had the same task and was able to make it work (without jQuery and with the help of maclema's reply), by using multipart/form-data content type:
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);
To go asynchronously or if you have more parts to send (e.g. multiple images) or if you want to work with the response, see How to send multipart/form-data form content by ajax (no jquery)?
Your servlet's doPost method would look something like:
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);
}
Hope this helps.
这篇关于保存HTML5&LT;画布&GT;图片瓦特/的Java Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!