AJAX jQuery头像上传

时间:2015-03-10 03:12:39

标签: javascript php jquery ajax

我一直试图找到一个非常基本的AJAX jQuery头像上传,我可以用于我的"设置"页面,以便用户可以上传头像,不幸的是我无法找到任何头像。

这是我的"功能"到目前为止上传头像

    function uploadAvatar(){
    $('#avatarDialog').fadeIn();
    $('#avatarDialog').html("Logging in, please wait....");
    dataString = $('#avatarForm').serialize();
    var postURL = $('#avatarForm').attr("action");
    $.ajax({
        type: "POST",
        url: site_url+"/libraries/ajax/image-upload.php",
        data:dataString,
        dataType:"json",
        cache:false,
        success:function(data){
            if(data.err){
                $('#avatarDialog').fadeIn();
                $('#avatarDialog').html(data.err);
            }else if(data.msg){
                $('#avatarDialog').fadeIn();
                $('#avatarDialog').html(data.msg);

                var delay = 2000;
                window.setTimeout(function(){          
                    location.reload(true);
                }, delay);
            }
        }
    });
    return false;
};

我的HTML /输入就是这个。

<form id="avatar_form" action enctype="multipart/form-data" method="post">
<input name="image_file" id="imageInput" type="file" />
<input type="submit"  id="submit-btn" onClick="uploadAvatar();" value="Upload" />

最后这是我的PHP代码(我这里什么都没有)

$thumb_square_size      = 200;
$max_image_size         = 500; 
$thumb_prefix           = "thumb_"; 
$destination_folder     = './data/avatars/';
$jpeg_quality           = 90; //jpeg quality


$return_json = array();
if($err==""){ $return_json['msg'] = $msg; }
else{ $return_json['err'] = $err; }
echo json_encode($return_json); 
exit;

那么我该如何开始呢。我不知道从哪里开始,我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

Bulletproof是一个很好的PHP图像上传类,它包含了常见的安全问题和实践,所以我们将在这里使用它,因为它也使整个过程更加简单和清洁。您需要在此处阅读此问题的已批准答案(https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form),以便更好地了解接受用户上传文件的风险。

下面的PHP非常基本,实际上只处理图像上传。如果映像成功上载,您可能希望保存在数据库或某种存储中生成的路径或文件名。

您可能还想更改上传图片的目录。为此,请将->uploadDir("uploads")的参数更改为其他相对或绝对路径。此值"uploads"会将图像上传到libraries/ajax/uploads目录。如果目录不存在,则防弹将首先创建它。

您需要下载防弹(https://github.com/samayo/bulletproof),并确保上传或放入libraries/bulletproof/。当您从github下载该类时,它将在ZIP存档中。解压缩zip存档并将bulletproof-master director重命名为plain bulletproof。将该目录放在libraries目录中。

HTML

    <form id="avatar_form" action enctype="multipart/form-data" method="post">
        <input name="image_file" id="imageInput" type="file" />
        <input type="submit"  id="submit-btn" value="Upload" />
    </form>

JS

$('#avatar_form').submit(function( event ){
    event.preventDefault();
    var formData = new FormData($(this)[0]); //use form data, not serialized string
    $('#avatarDialog').fadeIn();
    $('#avatarDialog').html("Logging in, please wait....");
    $.ajax({
        type: "POST",
        url: site_url + "/libraries/ajax/image-upload.php",
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            if(data.code != 200){ //response code other than 200, error
                $('#avatarDialog').fadeIn();
                $('#avatarDialog').html(data.msg);
            } else { // response code was 200, everything is OK
                $('#avatarDialog').fadeIn();
                $('#avatarDialog').html(data.msg);
                var delay = 2000;
                window.setTimeout(function(){          
                    location.reload(true);
                }, delay);
            }
        }
    });
    return false;
});

PHP

    //bulletproof image uploads
    //https://github.com/samayo/bulletproof
    require_once('../bulletproof/src/bulletproof.php');
    $bulletproof = new ImageUploader\BulletProof;

    //our default json response
    $json = array('code' => 200, 'msg' => "Avatar uploaded!");

    //if a file was submitted
    if($_FILES)
    {
        try
        {
            //rename the file to some unique
            //md5 hash value of current timestamp and a random number between 0 & 1000
            $filename = md5(time() . rand(0, 1000));
            $result = $bulletproof->fileTypes(["png", "jpeg"])  //only accept png/jpeg image types
                    ->uploadDir("uploads")  //create folder 'pics' if it does not exist.
                    ->limitSize(["min" => 1000, "max" => 300000])  //limit image size (in bytes) .01mb - 3.0mb
                    ->shrink(["height" => 96, "width" => 96])  //limit image dimensions
                    ->upload($_FILES['image_file'], $filename);  // upload to folder 'pics'

            //maybe save the filename and other information to a database at this point

           //print the json output                
           print_r(json_encode($json));        
        } 
        catch(Exception $e)
        {
            $json['code'] = 500;
            $json['msg'] = $e->getMessage();
            print_r(json_encode($json));
        }
    }
    else
    {
        //no file was submitted
        //send back a 500 error code and a error message
        $json['code'] = 500;
        $json['msg'] = "You must select a file";
        print_r(json_encode($json));
    }

如果图像未通过验证测试,Bulletproof将抛出异常。我们在try catch块中捕获异常,并将错误消息返回给JSON返回中的JavaScript。

代码的其余部分在Bulletproof github页面等方面得到了很好的评论,但如果有任何不明确的话,请发表评论。