I am trying to send a canvas PNG to a java servlet using ajax. Here is my javascript code:
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);
}
And the 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());
}
}
The problem is that getParameter("annotationImage")
returns null
, and I can't understand why: using browser debugger I can see annotationImage
and its value between the request parameters, so I am sure it is not null, but for some reason the parameter is not received by the Java Servlet.