我想将捕获的照片在画布中从JavaScript的浏览器上传到Node.js服务器。我没有找到合适的方法。请帮忙。非常感谢。

(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");
}


这段代码可以很好地下载捕获的图像,但是我无法将相同的图像上传到节点服务器。

最佳答案

这是答案代码。

在客户端

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');
}


在服务器端

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!");

            });
     }

}

07-24 00:03
查看更多