【问题标题】:Get the image sizes after being uploaded with ajax用ajax上传后获取图片大小
【发布时间】:2014-02-14 03:43:21
【问题描述】:

我正在开发一种允许用户使用 ajax 异步上传图像的工具。然后用户可以使用 jQuery UI 中的滑块调整他的图像大小。 但是,我在获取图像大小以调整图像大小的变量值方面遇到了一些问题,因为加载页面时没有图像,因此变量设置为零。

我想找到一种方法,在上传图片后立即刷新 orginalWidthorginalHeight

代码如下:

//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


    【解决方案1】:

    您可以使用您的 PHP 上传脚本来执行此操作。它可以返回描述图像大小的对象,并在 Ajax 成功函数中获取值。

    例如 PHP 可能包含这样的内容:

    $data = array('src' => $src,'width' => $width, 'height' => $height);
    echo json_encode($data);
    

    在 JS 中:

    ...
    dataType: 'json',
    ...
    success: function(data){
       $("#image").attr('src',data.src);
       console.log(data.height);
       console.log(data.width);
    }
    

    确实是这样的:

    $.ajax({
       url: "upload.php",
       type: "POST",
       data:  new FormData(this),
       dataType : 'json',
       contentType: false,
       cache: false,
       processData:false,
       success: function(data){
           $("#image").attr('src',data.src);
           console.log(data.height);
           console.log(data.width);
       },         
    });
    

    图片大小可以通过PHP函数getimagesize()获取。

    【讨论】:

    • 我想避免使用 PHP,但如果我没有任何选择,我会使用它。
    • 您可以使用load 函数来获取在浏览器中加载后的图像大小,但它并不总是有效。有很多问题,特别是当图像不是新的并且它在缓存中时。
    • @casusbelli:已编辑以回答您的问题。
    • 是的,问题是您更改了 ajax 请求中的 data 选项...您应该添加 dataType : 'json' - 两个不同的选项... data 是发送到服务器的内容通过POST 方法... 和dataType 是服务器返回结果的预期结果。编辑答案以显示完整的 JS 功能。
    • 没问题...很高兴我能帮上忙。祝你好运!
    【解决方案2】:

    您必须将图像大小调整为加载图像的大小

    success: function(data){
        $("#image").one('load',function() {
            var orginalWidth  = $("#image").width();
            var orginalHeight = $("#image").height();
        }).attr('src',data);
    },
    

    load()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-25
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多