【发布时间】:2014-02-14 03:43:21
【问题描述】:
我正在开发一种允许用户使用 ajax 异步上传图像的工具。然后用户可以使用 jQuery UI 中的滑块调整他的图像大小。 但是,我在获取图像大小以调整图像大小的变量值方面遇到了一些问题,因为加载页面时没有图像,因此变量设置为零。
我想找到一种方法,在上传图片后立即刷新 orginalWidth 和 orginalHeight。
代码如下:
//Upload the image with AJAX
$('#uploadForm').on('change', (function(e){
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#image").attr('src',data);
},
error: function()
{
}
});
}));
//Resize slider with jQuery UI
var orginalWidth = $("#image").width();
var orginalHeight = $("#image").height();
$("#infoSlider").text(orginalWidth + ', ' + orginalHeight + ', 100%');
$("#slider").slider({
value: 0,
min: -50,
max: 50,
step: 10,
slide: function (event, ui) {
var fraction = (1 + ui.value / 100),
newWidth = orginalWidth * fraction,
newHeight = orginalHeight * fraction;
$("#infoSlider").text(newWidth + ', ' + newHeight + ', ' + Math.floor(fraction * 100) + '%');
$("#image").width(newWidth);
}
});
编辑:
所以@FlashThunder 告诉我使用 PHP 来获取图像大小。但是我的 PHP 代码不起作用(JS 变量“未定义”)。
PHP 代码:
//Check if the file is well uploaded
if($_FILES['file']['error'] > 0) { echo 'Error during uploading, try again'; }
//We won't use $_FILES['file']['type'] to check the file extension for security purpose
//Set up valid image extensions
$extsAllowed = array( 'jpg', 'jpeg', 'png', 'gif' );
//Extract extension from uploaded file
//substr return ".jpg"
//Strrchr return "jpg"
$extUpload = strtolower( substr( strrchr($_FILES['file']['name'], '.') ,1) ) ;
//Check if the uploaded file extension is allowed
if (in_array($extUpload, $extsAllowed) ) {
//Upload the file on the server
$name = "img/{$_FILES['file']['name']}";
$result = move_uploaded_file($_FILES['file']['tmp_name'], $name);
if($result){
//echo "$name";
//Save the image size
//$filename = $_FILES['file']['tmp_name'];
list($width, $height) = getimagesize($name);
$data = array('src' => $name, 'width' => $width, 'height' => $height);
echo json_encode($data);
}
} else { echo 'File is not valid. Please try again'; }
JS 代码:
$.ajax({
url: "upload.php",
type: "POST",
//data: new FormData(this),
data : 'json',
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#image").attr('src', data.src);
var orginalWidth = data.width;
var orginalHeight = data.height;
alert(orginalWidth);
},
error: function()
{
}
});
【问题讨论】:
标签: javascript php jquery ajax jquery-ui