Reputation: 824
I'm using cropit.js for upload an image with php.
I just following this question How to crop and upload photo using cropit jquery plugin with php
This is my HTML code:
<form action="#" class="form-horizontal form-bordered" id="formUpload">
<div class="image-editor">
<div class="form-group">
<div class="col-xs-12">
<button id="fakeUpload" class="btn btn-default col-xs-12"><i class="fa fa-upload"></i> Scegli la foto da caricare</button>
<input type="file" class="cropit-image-input" name="bannerUpload" id="bannerUpload" style="display:none;">
</div>
</div>
<div class="form-group">
<div class="col-xs-12 text-center">
<div class="cropit-image-preview"></div>
</div>
</div>
<div class="form-group">
<label for="zoomUpload" class="col-md-2">Zoom</label>
<div class="col-md-10 text-center">
<input type="range" class="cropit-image-zoom-input" id="zoomUpload">
</div>
</div>
<div class="form-group">
<div class="col-xs-12 text-center">
<input type="hidden" name="image-data" class="hidden-image-data" />
<button type="submit" class="btn btn-primary col-xs-12"><i class="fa fa-cloud-upload"></i> Carica</button>
</div>
</div>
</div>
</form>
and this the JS:
$('#formUpload').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
//$('#result-data').text(formValue);
$.ajax({
type: "POST",
url : "cpu/uploadBanner.php",
data: formValue,
success: function(msg){
//$("#AjaxResult").html(msg);
alert(msg);
}
})
// Prevent the form from actually submitting
return false;
});
Finally the PHP code:
<?php
include '../inc/config.php';
if($_SERVER['REQUEST_METHOD']=="POST"){
$encoded = $_POST['image-data'];
//decode the url, because we want to use normal charackters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$file = 'data.png';
//make sure you are the owner and have the rights to write content
file_put_contents($file, $data);
echo 'ok';
}else{
echo "Non dovresti essere quì!";
}
?>
When the form is submitted I see the new image called 'data.png' but I see all black, don't save the image correcty or what? The folder have 777 permission.
Upvotes: 1
Views: 2489
Reputation: 84
Try this PHP code:
<?php
include '../inc/config.php';
if($_SERVER['REQUEST_METHOD']=="POST"){
$encoded = $_POST['image-data'];
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $encoded);
//decode the image and finally save it
$data = base64_decode($exp[1]);
$file = 'data.png';
//make sure you are the owner and have the rights to write content
file_put_contents($file, $data);
echo 'ok';
}else{
echo "Non dovresti essere quì!";
}
?>
Upvotes: 2