dongzong5017
2015-03-10 03:12
浏览 257
已采纳

AJAX jQuery头像上传

I've been trying to find a very basic AJAX jQuery Avatar Uploading that I can use for my "settings" page so users can upload an avatar and unfortunately I can't find any.

This is my "function" so far for uploading the avatar

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

For my HTML/Input is this.

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

And finally this is my PHP code (I have nothing here)

$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;

So how do I start this really. I just don't know where to start, I don't know exactly what to do.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanjuebiao6730 2015-03-10 06:12
    最佳回答

    Bulletproof is a nice PHP image upload class which encorporates common security concerns and practices, so we will use it here as it also makes the whole process much simpler and cleaner. You will want to read the approved answer on this question here (https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form) to better understand the risks of accepting file uploads from users.

    The PHP below is really basic and really only handle the image upload. You would want to save the path or the file name that was generated in a database or in some kind of storage if the image is uploaded successfully.

    You may also want to change the directory in which the image is uploaded to. To do this, change the parameter for ->uploadDir("uploads") to some other relative or absolute path. This value "uploads" will upload the image to the libraries/ajax/uploads directory. If the directory does not exist, bulletproof will first create it.

    You will need to download bulletproof (https://github.com/samayo/bulletproof) and make sure to upload or place it in libraries/bulletproof/. When you download the class from github it will be in a ZIP archive. Extract the zip archive and rename bulletproof-master director to just plain bulletproof. Place that directory in the libraries directory.

    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 will throw an exception if the image does not pass the validation tests. We catch the exception in the try catch block and return the error message back to the JavaScript in the JSON return.

    The rest of the code is commented pretty well from the Bulletproof github page etc, but comment if anything is not clear.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题