Reputation:
I want to upload the captured photo in canvas from browser in javascript to nodejs server. I am not getting a proper method. Please help. Thank you so much.
(function(){
var video=document.getElementById('video'),
canvas = document.getElementById('canvas'),
vendorUrl = window.URL || window.webkitURL;
context = canvas.getContext('2d');
//photo = document.getElementById('photo');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false
}, function(stream){
video.srcObject=stream;
video.play();
}, function(error){
});
document.getElementById('capture').addEventListener('click',function(){
context.drawImage(video,0,0,400,300);
// photo.setAttribute('src',canvas.toDataURL('image/png'));
download();
});
})();
function download() {
var download = document.getElementById("capture");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.png");
}
This code works fine to download a captured image but I am not getting a way to upload same image to node server.
Upvotes: 2
Views: 1576
Reputation:
Here is the answer code.
At client side
function covertImage() {
var image = document.getElementById("canvas").toDataURL("image/png");
sendMessage(image);
}
//Sending image data to server
function sendMessage(image){
var msg = JSON.stringify(image);
var xhr = new XMLHttpRequest();
xhr.open('POST', true);
xhr.send(msg);
alert('file is saved');
}
At Server Side
http.createServer(function (request, response) {
var post='';
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
//-------------parsing data from json to string-------------------------
post = JSON.parse(body);
var data = post.replace(/^data:image\/\w+;base64,/, "");
var buf = Buffer.from(data, 'base64');
writeFileToSystem(buf);
});
}
//----------saving image to server side folder------------------
function writeFileToSystem(buf)
{
fs.writeFile("images/image.png", buf, function(err) {
console.log("The file was saved!");
});
}
}
Upvotes: 6
Reputation: 2846
the DataURL is a string with the content-type and (generally) a base64-encoded string of the data which looks something like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z
So there are a two things you can do with this:
You can decide to parse it by the client side and send the parsed result to your nodejs server with an xhr request
You can send the string immediately with an xhr request parsing it on your server side with something like data-url-parser
Hope this helps getting you in the right direction
Upvotes: 0