我使用cropit.js上传带有php的图片。
我只是关注这个问题 How to crop and upload photo using cropit jquery plugin with php
这是我的HTML代码:
<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>
这就是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;
});
最后是PHP代码:
<?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ì!";
}
?>
提交表单后,我会看到名为&#39; data.png&#39;的新图片。但我看到所有黑色,不保存图像正确或什么?该文件夹具有777权限。
答案 0 :(得分:2)
试试这个PHP代码:
<?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ì!";
}
?>