我想通过ajax上传和裁剪图片。
请建议我如何做到这一点。
答案 0 :(得分:3)
要上传图片,您需要javascript进程处理上传,如果您使用jquery库,有很多插件可以执行此操作。 要处理上传过程,您需要PHP脚本。您正在从ajax向php脚本发送请求并执行上传。
要裁剪图像,您需要裁剪工具或裁剪脚本,这是一个很酷的http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/
处理裁剪后的图像后,需要通过jquery uploader插件或其他jquery或javascript ajax代码执行上传过程(php)。
答案 1 :(得分:0)
Here is the code Jquery + PHP [Cake PHP]
View file upload.ctp
<script type="text/javascript" src="http://demos.9lessons.info/ajaximageupload/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').on('change', function(){
$("#preview").html('');
$("#preview").html('<img src="/images/ajax-loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({target: '#preview',success: showResponse}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='/media/upload'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'></div>
create a function with name upload in Media controller
function upload(){
$this->layout = '';
$session_id='1'; // User session id
$path = "images/media/images/original/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
//pr($_FILES);die;
//if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)){
if($size<(1024*1024)) { // Image size max 1 MB
$txt=str_replace(" ","_",$txt);
$actual_image_name = $txt."_".time().".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
App::import('Vendor', 'resize');
if(move_uploaded_file($tmp, $path.$actual_image_name)) { //Code for image resize
//mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
// save this to DB into Temp Selection table set USer wise and Capsule or individual Board wise
echo "<img src='/images/media/images/".$actual_image_name."' class='preview'><br/><a href='javascript:void(0);' id='upload_submit'>Submit</a>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file fo`enter code here`rmat..";
}
else
echo "Please select image..!";
exit;
}
}