【问题标题】:Uploaded image taken from webcam is corrupted when uploaded to server从网络摄像头拍摄的上传图像在上传到服务器时已损坏
【发布时间】:2019-02-07 14:40:30
【问题描述】:

我正在尝试上传从网络摄像头拍摄的图像。我使用画布显示该图像并通过 POST 方法将 base64_encoded json 数据发送到 PHP,因此在 PHP 中解码数据并尝试通过 file_put_contents 创建图像。但上传的图像每次都损坏。我也在 PHP 中使用了 header("Access-Control-Allow-Origin: *") 。我还检查了服务器中是否启用了 file_get_contents。可能是什么错误?请帮忙。

我的代码是:

 JS:

// Trigger photo take

var imagedata;
document.getElementById('snap').addEventListener('click', function() {
   $('#canvas').show();
   context.drawImage(video, 0, 0, 640, 480);
   $('#upload-button').removeAttr("disabled");
   var image = new Image();
   image.src = canvas.toDataURL();
   imagedata = image.src;
   $('#webimage').val(imagedata);
}); 

PHP:
header("Access-Control-Allow-Origin: *");
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$base = $input_data['image'];
$destination_directory = "uploads/";
$file_name  =   time();
$file_name = $file_name.'.png';
$targetPath = $destination_directory . $file_name;
$input_data = base64_decode($base);
file_put_contents($targetPath, $input_data);

【问题讨论】:

    标签: php webcam


    【解决方案1】:

    你检查过data url of an image吗?它看起来像这样:

    image/gif;base64,R0lGODlhyAAiALM...DfD0QAADs=
    

    如您所见,图像二进制内容的实际 base64 编码表示在逗号之后开始。你所要做的就是改变:

    $base = $input_data['image'];
    

    到:

    // php >= 5.4
    $base = explode(',', $input_data['image'])[1];
    
    // php < 5.4
    list (, $base) = explode(',', $input_data['image']);
    

    所以base64_decode 函数接收到正确的base64 字符串。

    您的脚本中也缺少正确的验证:

    • 验证 JSON 输入是否正确解码
    • 验证 image 键是否存在于结果数组中
    • 验证base64_decode 确实解码了字符串
    • 验证生成的图像是有效的图像(恶意用户可以在图像中嵌入 PHP 代码)

    通过这种方式,您可以 99% 确定您的服务器将来不会受到威胁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-06
      • 2017-12-25
      • 2018-01-19
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多