如何正确将base64编码的图像上传到文件服务器?

时间:2017-06-15 07:43:20

标签: javascript php jquery validation encoding

我正在使用CropIt JQuery插件来裁剪和上传照片。选择照片返回base64编码图像后的插件。像这样:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA....

我正在使用Ajax将它发送到PHP:

$.ajax({
    type: 'post',
    url: 'upload.php',
    data: $('form').serialize(),
    success: function (data) {      
        $('.image-editor').cropit('imageSrc', 'images/' + data );
        $('#change').css("background-image", "url('images/" + data + "')");
        modal.style.display = "none";
    }
});

如何通过PHP正确验证图像并将其存储到文件服务器?

现在我正在使用这样的PHP而且它正在工作,但正如我之前所读过的,这种方法并不安全且没有任何验证:

function decode ($code) {
    list($type, $code) = explode(';', $code);
    list(, $code)      = explode(',', $code);
    $code = base64_decode($code);

    file_put_contents('images/filename.jpg', $code); // there filename static for example
}
$testdata = $_POST["image-data"];
decode($testdata);

echo "filename.jpg";

我应该使用move_uploaded_file()代替file_put_contents()吗?但是我怎么能用base64编码的图像实现呢?

我看到了验证这样的文件的方法,但我不知道如何将它与base64编码的图像一起使用:

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 100000)
    && in_array($extension, $allowedExts)){

    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } 
    else {
        $fileName = $temp[0].".".$temp[1];
        $temp[0] = rand(0, 3000); //Set to random number
        $fileName;

        if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
        }
        else {
            move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
            echo "Stored in: " . "../img/imageDirectory/" . $_FILES["file"]["name"];
        }
    }
}
else {
    echo "Invalid file";
}

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

$encoded = $_POST['image-data'];
$exp = explode(',', $encoded);
$data = base64_decode($exp[1]);
$file = 'images/filename.jpg';
file_put_contents($file, $data);