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.

duanjieyi6582
duanjieyi6582 就像我说的,我犯了错误xD....
5 年多之前 回复
duangonglian6028
duangonglian6028 你有onClick=“avatar();”但我没有看到一个名为avatar()的函数,但是有一个名为uploadAvatar()的函数。
5 年多之前 回复
dongying6896
dongying6896 是的,我知道它没有,它并不是假设在那里。呵呵,因为提交输入中的login()将获取执行操作所需的文件。即使它在那里也没有做任何事情,只是忘了删除它。
5 年多之前 回复
dongzhiqi0332
dongzhiqi0332 您的表单没有任何动作-<formid=“avatar_form”actionenctype=“multipart/form-data”method=“post”>
5 年多之前 回复

1个回答

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.

dragoninasia2014
dragoninasia2014 我很高兴我的代码很有用,我已经完成了制作v-2.0,确保在一两个星期之后在github上查看它。 它比当前版本更好,具有非常简化的语法和一些附加功能。 如果您有任何愿望清单,请告诉我;)
5 年多之前 回复
dongpu1881
dongpu1881 谢谢Sam,我在几个项目中使用了Bulletproof,所以我很乐意在适用时传播这个词。 Bulletproof会为我们生成一个名称,这很好,但我想向OP演示如何创建自己独特的字符串/文件名以供进一步参考。 感谢您提供Bulletproof。
5 年多之前 回复
drui0508
drui0508 如果你使用没有第二个参数的upload()方法,BP将自己生成一个名称,如README页面所示。 您不必自己生成名称。 除了那个非常好的答案+1来自我
5 年多之前 回复
dongyi8416
dongyi8416 让我们在聊天中继续讨论。
5 年多之前 回复
donglaohua1671
donglaohua1671 你在那里用什么编辑? 我唯一想到的就是它只是突出显示该行是要么没有从相对路径加载防弹库,要么它不喜欢该方法的链接。 这有什么不同吗? $ result = $ bulletproof-> fileTypes([“png”,“jpeg”]) - > uploadDir(“uploads”) - > limitSize([“min”=> 1000,“max”=> 300000]) - >收缩 ([“height”=> 96,“width”=> 96]) - > upload($ _ FILES ['image_file'],$ filename);
5 年多之前 回复
dsaff82024
dsaff82024 我删除了评论,仍然是同一个问题。 i.gyazo.com/df4e30c0be20f6202f12311323d4cfa5.png
5 年多之前 回复
doudao1922
doudao1922 这也可能对你有所帮助,我在Firefox中检查了Console,我得到了500内部服务器错误:i.gyazo.com/1ebe95bf6ee5010cb06663e0d84d5a41.png ...我正在使用Adobe Dreamweaver CS6
5 年多之前 回复
dongtanlin0765
dongtanlin0765 你在那里用什么编辑? 可能是编辑器不喜欢方法的链接方式,或者字符串中有某种新行或返回导致解析错误。 删除所有评论并尝试此操作。
5 年多之前 回复
dongyue9860
dongyue9860 我不知道它是什么样的错误,我尝试了常见的技巧让它工作,它没有做任何事情。 i.gyazo.com/485be5cee9e7587d609204135cdfa9a0.png
5 年多之前 回复
duanbipu1720
duanbipu1720 你收到的错误是什么? 我能够使用上面的代码成功上传图像。
5 年多之前 回复
doumie7914
doumie7914 此外,代码的这一部分有错误$ result = $ bulletproof-> fileTypes([“png”,“jpeg”])//只接受png / jpeg图像类型 - > uploadDir(“uploads”)//创建 文件夹'pics'如果不存在。 - > limitSize([“min”=> 1000,“max”=> 300000])//限制图像大小(以字节为单位).01mb - 3.0mb - > shrink([“height”=> 96,“width”= > 96])//限制图像尺寸 - >上传($ _ FILES ['image_file'],$ filename); //上传到文件夹'pics'
5 年多之前 回复
douqipi9704
douqipi9704 哇,这太棒了。 感谢代码中的评论以及解释所有内容。 我肯定会用这个。 谢谢你的一切,+ 9K
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐