Search code examples
javascriptajaxhtmlwebsocketserversocket

Uploading an image obtained from a canvas to a server


I have seen this question asked before but I think I have a different case so I am goingt o post it any way. So my question is very simple as and it is exactly as the topic says. I have a image that I write to canvas and I can convert it to data and them save it on a remote server.

I tried AJAX XHttp as follows

imageformdata.append("FILE_NAME", filename);          
imageformdata.append(filename, image);
var oReq = new XMLHttpRequest();
oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      document.getElementById('response').innerHTML = "Uploaded!";
    } else {
      document.getElementById('response').innerHTML = "not Uploaded!";
    }
 };
oReq.open("POST", "http://localhost:18000/");
oReq.send(imageformdata);

But I can not edit the server to avoid Access-Control-Allow-Origin, so to me it seems AJAX is out of the question. I would like to know if my thinking is right or is there another way to go around this issue.

Second option that I tried to do was manually creating a form and then including input type file and then I realize I can not select a file with Javascript or can I. If yes how hope some one can help me. My code is as follows.

var form= document.createElement('form');
var input = document.createElement('input');
input.type = 'file';
form.method = "POST";
form.action = "http://localhost:17999/";            
var image = new Image();
image.onload = function(){
    localcontext.drawImage(image,0, 0);
};
image.src = "img/1.jpg";          

input.value = localcanvas.toDataURL('image/jpeg');
form.appendChild(input);
var now = new Date();
filename = filename+"_"+now.getFullYear()+ now.getMonth() +now.getDate()+"_"+now.getHours()+now.getMinutes()+now.getSeconds()+ ".jpg";
form.appendChild(input);
document.body.appendChild(form);
form.submit();

So as a workaround I think my option is to go for websocket and create a client server application for web client to communicate with a Server socket (Java, )I have not done websockets before so please please let me know if this is doable or is the Access-Control-Allow-Origin issue applies for this as well.


Solution

  • As It it turned out, web socket solution worked like a charm for me. I created binary stream from the web client and then read it from the server socket in the python back end. Only issue is that binary conversion and the transfer adds immense amount of overhead. If anyone needs codes just reply.