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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型