如何使用toDataURL()将图像从网络摄像机画布发布到服务器? javascript

时间:2018-07-06 13:25:16

标签: javascript node.js image cloudinary

我想通过网络摄像机发送捕获的图像,然后发送到服务器以存储该图像。

function captureAndSendToServer() {
const player = document.getElementById('player')
const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')
context.drawImage(player, 0, 0, canvas.width, canvas.height)
var image = canvas.toDataURL("image/png")
// var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");

axios
  .post('http://localhost:3000/sendImageToCloudinary', image)
  .then(response => {
  console.log(response)
})
}

我使用Cloudinary存储服务器代码Image:

exports.sendImageToCloudinary = (req, res) => {
  console.log(req.body)
  cloudinary.v2.uploader.upload(req.body,
    function (error, result) {
      if (err) throw error
      console.log(result)
      res.json(result)
    })
}

错误是

PayloadTooLargeError: request entity too large

我已经尝试过console.log(image)并输出数十万个单词。

那么,什么是正确的方法,谢谢你,

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-

    var file = <your_file>;

    var formdata = new FormData();

    formdata.append('file', file);
    formdata.append('cloud_name', '<cloud_name>');
    formdata.append('resource_type', 'image');
    formdata.append('upload_preset', '<upload_preset>');



    var xhr = new XMLHttpRequest();
    xhr.open('POST', "https://api.cloudinary.com/v1_1/<cloud_name>/image/upload",true);


    xhr.onload = function () {
    // do something to response
        //console.log(this.responseText);
    };

    xhr.send(formdata);