XmlHttpRequest 请求元素是 None

XmlHttpRequest request element is None

我正在使用 Django 并尝试使用 XMLHttpRequest 将网络摄像头数据发送到后台 (view.py) 以便处理每一帧。我遵循 this link 并且大多数人针对我的问题提出了类似的方法。

$(document).ready(function(){
  $('#trigger_button').click(function(){
    navigator.mediaDevices.getUserMedia(constraints)
    .then(stream => {
      document.getElementById("myVideo").srcObject = stream;
    })
    .catch(err => {
      alert('navigator.getUserMedia error: ', err)
    });
    drawCanvas.width = v.videoWidth;
    drawCanvas.height = v.videoHeight;
    imageCanvas.width = uploadWidth;
    imageCanvas.height = uploadWidth * (v.videoHeight / v.videoWidth);
    drawCtx.lineWidth = 4;
    drawCtx.strokeStyle = "cyan";
    drawCtx.font = "20px Verdana";
    drawCtx.fillStyle = "cyan";
    imageCanvas.getContext("2d").drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth));

    imageCanvas.toBlob(postFile, 'image/jpeg');
  });
});
function postFile(file) {
  var formdata = new FormData();
  formdata.append("image", file);
  formdata.append("threshold", scoreThreshold);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', apiServer, true);

  xhr.onload = function () {
    if (this.status === 200) {
      var objects = JSON.parse(this.response);
      drawBoxes(objects);
      imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth));
      imageCanvas.toBlob(postFile, 'image/jpeg');
    }
    else {
      alert(this.status);
    }
  };
  xhr.send(formdata);
}

然后,我尝试访问 view.py 中请求中的数据,如下所示:

def control4(request):
    print(request.POST.get('image'))
    print(request.POST.get('threshold'))
    return render(request, 'local.html')

但是,虽然request.Post.get('threshold')returns一个值,request.POST.get('image')returnsNone .此外,此方法重复三次,然后停止发送反馈。我的意思是,control4 函数打印了 3 次(我认为它应该在相机关闭之前有效)。

谁能知道问题出在哪里?

谢谢你,最好的。

您必须在 request.FILES 中查找图像

def control4(request):
    print(request.FILES['image'])
    print(request.POST.get('threshold'))
    return render(request, 'local.html')