1

I am trying to upload a canvas image (which was drawn from a webcam shot) into a file and then save it to servlet.

JSP file:

<form id="submissionForm" action="/PSA/SaveImageServlet" method="POST" 
          name="registrationForm" enctype="multipart/form-data">
          <input name="camera1Image" type="image" id="camera1ImageID" style="visibility:hidden" />
          <input name="camera1File"  type="file"  id="camera1FileID"  style="visibility:hidden" />
          <img   name="camera1Img"   src="" id="camera1ImgID" style="visibility:hidden" />
</form>

Javascript:

var canvas1 = document.querySelector('#canvas1');
var ctx = canvas1.getContext('2d');
w = canvas1.width;
h = canvas1.height;
ctx.drawImage(video1, 0, 0, w, h);
var dataUrl = canvas1.toDataURL("image/jpeg", 0.95);
var image = new Image();
image.src = dataUrl;
$("#camera1ImageID").attr("src", image.src);
$("#camera1FileID").attr("val", image.src);
$("#camera1ImgID").attr("src", image.src);

and on the servlet I have outputs: contentType: application/octet-stream size: 0

I managed to submit only an image data with ajax , but is it possible to do it without ajax?

Thank you very much

Talgat
  • 135
  • 11
  • `src` attribute of input can only be used with `input type='image'`. see here: [https://www.w3schools.com/tags/att_input_src.asp](https://www.w3schools.com/tags/att_input_src.asp). So having a try to set `value` attribute for your file input with `image.src` and see would it work. – HowieChih May 20 '17 at 04:02
  • Thank you, I tried according to your advice (I have edited the post), but still can't see any files or images in my servlet. Size is "0" and content type is "application/octet-stream" – Talgat May 21 '17 at 06:39
  • I made a mistake which set `value` attribute can not convert canvas image to `input file` and the conversion maybe complex. So eaiser way to do this is just send the `dataUrl` value(the value is char sequence) to Servlet. There are two ways to send it, one is setting value to a `input='hidden'` in form and submit with a submit button, anothre way is sending with Ajax. After Servlet get the `dataUrl` String value, you can conver it to a File image with Java code. [http://stackoverflow.com/a/24163254/5374508](http://stackoverflow.com/a/24163254/5374508) maybe useful. – HowieChih May 21 '17 at 16:50
  • Thank you! Your last comment was helpful! – Talgat May 22 '17 at 11:11

1 Answers1

0

There are two ways to send it, one is setting value to a input='hidden' in form and submit with a submit button, another way is sending with Ajax. After Servlet gets the dataUrl String value, you can convert it to a File image with Java code. http://stackoverflow.com/a/24163254/5374508 maybe useful.

HaoChih May 21 at 16:50

Talgat
  • 135
  • 11