Issue
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.
Solution
I found out the reasons why it didn't work.
To avoid parsing JSON I send the data to the server without setting any parameter, writing data: image
instead of JSON formatted data: {annotationImage: image}
to avoid JSON parsing in the servlet.
In the java servlet I get the entire request body, remove the content-type declaration and finally decode and save the image. Here is the code:
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());
}
}
Answered By - Luca Maltagliati
Answer Checked By - Clifford M. (JavaFixing Volunteer)