AJAX jQuery Avatar Uploading


AJAX jQuery Avatar Uploading

我一直在尝试找到一个非常基本的 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;

那么我该如何真正开始呢?我只是不知道从哪里开始,我不知道该怎么做。

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存档并将防弹主导演重命名为普通防弹。将该目录放在库目录中。

.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));
    }

如果图像未通过验证测试,防弹将引发异常。我们在 try catch 块中捕获异常,并在 JSON 返回中将错误消息返回到 JavaScript。

其余代码在防弹 github 页面等中得到了很好的注释,但如果有什么不清楚的地方,请注释。