【问题标题】:Uploading an image from canvas to PHP server using AJAX使用 AJAX 将图像从画布上传到 PHP 服务器
【发布时间】:2016-11-02 04:10:12
【问题描述】:

在我正在构建的软件中,我使用网络摄像头拍照并从那里上传到 PHP 服务器以供以后使用。我已经使用表单成功地将图像从我的计算机上传到服务器,但是由于我要上传的图像已经预先确定,我一直在研究使用 AJAX。我从网络摄像头拍摄快照的代码如下:

 var video = document.getElementById('video');

        // Get access to the camera!
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            // Not adding `{ audio: true }` since we only want video now
            navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) {
                video.src = window.URL.createObjectURL(stream);
                video.play();
            });
        }

        // Elements for taking the snapshot
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var video = document.getElementById('video');

        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function () {
            var img = context.drawImage(video, 0, 0, 640, 480);
        });

        document.getElementById("capture").addEventListener("click", function () {
            context.drawImage(video, 0, 0, 640, 480);
            //var capture = canvas.toDataURL();
        });

这是我保存这张图片的 php 代码:

  <?php
    if (isset($_POST['upload'])) {
        $image_name = $_FILES['image']['name'];
        $image_name = $_FILES['image']['type'];
        $image_name = $_FILES['image']['size'];
        $image_tmp_name = $_FILES['image']['tmp_name'];

        if ($image_name == '') {
            echo "<script>alert('Please select an image.')</script>";
            exit();
        } else {
            move_uploaded_file($image_tmp_name, "pictures/$image_name");
            echo "Image uploaded succesfully.";
            echo "<img src= 'pictures/$image_name'>";
        }
    }
    ?>

我确信这两个代码都可以工作,因为我已经分别测试了它们。如前所述,我正在尝试使用 AJAX 将它们联系在一起。我为此找到的示例代码是:

function saveImage() {
            var capture = canvas.toDataURL("image/png");
            var xmlHttpReq = false;
            if (window.XMLHttpRequest) {
                ajax = new XMLHttpRequest();
            }

            else if (window.ActiveXObject) {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            ajax.open('POST', 'picture.php', false);
            ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            ajax.onreadystatechange = function () {
                console.log(ajax.responseText);
            }
            ajax.send("imgData=" + capture);
        }

我在按钮中使用了 onClick = "saveImage()" 来尝试调用函数并将图像上传到服务器。当我按下按钮时,文件似乎根本无法访问服务器。有什么我在这里遗漏的东西可以让它全部工作吗?

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    您不会将其作为文件发送,而是将其作为一个使用 Blob 或 File 对象发送

    var blob = new Blob([capture ], {type: 'application/octet-binary'});
    var form = new FormData();
    var fileName = 'snap.png';    //filename
    form.append('something', blob, fileName);
    

    在服务器上解码并保存

    $dest = 'uploads/'.$_FILES['something']['name'];
    
    move_uploaded_file($_FILES['something']['tmp_name'],$dest);
    $file = file_get_contents($dest);
    $tmp = explode(',',$file);                       //remove data: header
    file_put_contents($dest,base64_decode($tmp[1])); //decode base64 n save
    

    【讨论】:

      【解决方案2】:
      // Create a blob instead of dataURL (that way you save ~3x bandwidth and CPU)
      canvas.toBlob(function(blob) {
        var fd = new FormData()
      
        // append the blob to a multipart form
        fd.append('image', blob, 'snapshot.png')
      
        // send the form to the server using ajax
        fetch('picture.php', {method: 'post', body: fd})
      })
      

      【讨论】:

      • 在这种情况下,由于 fetch 会将表单发送到服务器,我会使用它而不是我的 saveImage 函数中的代码吗?
      • 是的,你可以。但请注意,并非所有浏览器都支持 fetch caniuse
      • 我可能遗漏了一些东西,但是当我在函数中插入您上面提供的代码时,我似乎没有将图像发送到服务器。
      猜你喜欢
      • 2016-03-16
      • 2014-09-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2018-07-15
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多