我正在使用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";
}
最佳答案
尝试下面的代码:
$encoded = $_POST['image-data'];
$exp = explode(',', $encoded);
$data = base64_decode($exp[1]);
$file = 'images/filename.jpg';
file_put_contents($file, $data);
关于javascript - 如何正确地将base64编码的图像上传到文件服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44561579/