简体   繁体   English

使用Javascript上传个人资料图片

[英]Uploading profile picture using Javascript

I would like to upload a profile picture for my project from user's end.我想从用户端上传我的项目的个人资料图片。

My HTML code for this is我的 HTML 代码是

   <div class=" col-xs-12">
        <div class="thumbnail">

        <!--<img id="profilepic" class="profilepicholder" height="200" width="200">-->

        <img id="profilepic" class="profilepicholder" src="#" alt="your image" height="200" width="200" />
        <input type='file' />
        <button id="save" class="save btn btn-primary  btn-block">Save</button>


                                      </div>
                                   </div>

And Javascript for uploading file is用于上传文件的 Javascript 是

  $(function () {
        $(":file").change(function () {
            if (this.files && this.files[0]) {
                var reader = new FileReader();
                reader.onload = imageIsLoaded;
                reader.readAsDataURL(this.files[0]);
            }
        });
    });

    function imageIsLoaded(e) {
        $('#profilepic').attr('src', e.target.result);
    };

    $(document).ready(function () {



        profile_url = "";
        upload_counter = 0;
        uploaded_counter = 0;



        /*
            Function to carry out the actual PUT request to S3 using the signed request from the app.
        */
        function upload_file(file, signed_request, url, type) {
            var xhr = new XMLHttpRequest();
            xhr.open("PUT", signed_request);
            xhr.setRequestHeader('x-amz-acl', 'public-read');
            xhr.onload = function () {
                if (xhr.status === 200) {

                    console.log(url)
                        //this is the URL , keep the value in the variable
                    $(document).ready(function () {
                        /*  $("#social_card").attr("value", url);
                            console.log("oi" + url);
                        */ //national_id_url = url;
                        upload_counter = upload_counter + 1;
                        console.log(upload_counter);


                        if (type == "profilepic") {
                            profile_url = url;
                        }



                    });

                }
            };
            xhr.onerror = function () {
                alert("Could not upload file.");
            };
            xhr.send(file);
        }

        /*
            Function to get the temporary signed request from the app.
            If request successful, continue to upload the file using this signed
            request.
        */
        function get_signed_request(file, type) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "/sign_s3?file_name=" + $(".username").val() + "/" + file.name + "&file_type=" + file.type);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);

                        upload_file(file, response.signed_request, response.url, type);
                    } else {
                        alert("Could not get signed URL.");
                    }
                }
            };
            xhr.send();
        }

        /*
           Function called when file input updated. If there is a file selected, then
           start upload procedure by asking for a signed request from the app.
        */
        function init_upload() {
            console.log("here");


            var profilepic_files = document.getElementById("profilepic").innerHTML;
            var profilepic_file = profilepic_files[0];
            if (profilepic_file == null) {
                //alert("No file selected.");


            } else {

                get_signed_request(profilepic_file, "profilepic");
            }



        }



        var myInterval;


        $("#save").mouseup(function () {

            $('.loadingcustom').css({
                display: 'block',
                position: 'absolute',
                width: '200vw',
                                });

                init_upload();

            var profilepic_files = document.getElementById("profilepic").innerHTML;
            var profilepic_file = profilepic_files[0];
            if (profilepic_file != null) {
                uploaded_counter = uploaded_counter + 1;

            }

            myInterval = setInterval(function () {
                console.log(upload_counter);
                console.log(uploaded_counter);

                if (upload_counter == uploaded_counter) {
                    upload_counter = uploaded_counter + 1;
                    var userData = {

                        "profile_url": profile_url,

                    };

                    console.log(userData);

                    $.ajax({
                        type: "POST",
                        url: "/users/",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(userData),
                        success: function (data) {
                            console.log("user created");
                            $('.alert').show();
                            $('.loadingcustom').hide();
                            $('.savebtn').show();
                            clearInterval(myInterval);

                            setTimeout(function () {
                                window.location.reload();
                            }, 2000);

                        }
                    });

                }


            }, 3000);

            });
    });

I am uploading this file to MongoDB.我正在将此文件上传到 MongoDB。 My requirement is to upload picture for particular user.我的要求是为特定用户上传图片。

Yes!是的! I could do that.我可以那样做。 Would like to share my code with you :) This code is for uploading files and update uploaded files.想与您分享我的代码:) 此代码用于上传文件和更新上传的文件。

<script>
    $(document).ready(function () {
        var get_params = function (search_string) {
            var parse = function (params, pairs) {
                    var pair = pairs[0];
                    var parts = pair.split('=');
                    var key = decodeURIComponent(parts[0]);
                    var value = decodeURIComponent(parts.slice(1).join('='));
                    // Handle multiple parameters of the same name
                    if (typeof params[key] === "undefined") {
                        params[key] = value;
                    } else {
                        params[key] = [].concat(params[key], value);
                    }
                    return pairs.length == 1 ? params : parse(params, pairs.slice(1))
                }
                // Get rid of leading ?
            return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
        }
        var params = get_params(location.search);
        var usersId = params['id'];
        var uid = usersId.replace(/\s+/g, "");
        var username;
        var profilepicture;
        var passcard;
        $.ajax({
            type: "GET",
            url: "/users/" + uid,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data.passport_url);
                username = data.username;
                $('#nidimage').attr('src', data.nid_url);
                $('#passcard').attr('src', data.passport_url);
                $('#birthimage').attr('src', data.birth_url);
                $('#vehiclelicenceimage').attr('src', data.vehicle_url);
                $('#drivinglicimage').attr('src', data.driving_url);


            }
        });
        national_id_url = "";
        passport_url = "";
        birth_certificate_url = "";
        driving_license_url = "";
        vehicle_license_url = "";
        profile_pic_url = "";
        upload_counter = 0;
        uploaded_counter = 0;
        /*
            Function to carry out the actual PUT request to S3 using the signed request from the app.
        */
        function upload_file(file, signed_request, url, type) {
            var xhr = new XMLHttpRequest();
            xhr.open("PUT", signed_request);
            xhr.setRequestHeader('x-amz-acl', 'public-read');
            xhr.onload = function () {
                if (xhr.status === 200) {
                    //  console.log(url)
                    //this is the URL , keep the value in the variable
                    var userData;
                    if (type == "nid") {
                        national_id_url = url;
                        userData = {
                            nid_url: national_id_url
                        };
                    } else if (type == "passport") {
                        passport_url = url;
                        userData = {
                            passport_url: passport_url
                        };
                    } else if (type == "birth") {
                        birth_certificate_url = url;
                        userData = {
                            birth_url: birth_certificate_url
                        };
                    } else if (type == "vehicle") {
                        vehicle_license_url = url;
                        userData = {
                            vehicle_url: vehicle_license_url
                        };
                    } else if (type == "driving") {
                        driving_license_url = url;
                        userData = {
                            driving_url: driving_license_url
                        };
                    } else if (type == "propic") {
                        profile_pic_url = url;
                        userData = {
                            profile_url: profile_pic_url
                        };
                    }
                    // console.log("pp"+ passport_url);
                    // console.log("boo "+uid);
                    $.ajax({
                        type: "PUT",
                        url: "/users/" + uid,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(userData),
                        success: function (data) {
                            console.log("user Updated");
                            $('.loadingcustom').css({
                                display: 'none',



                            });
                            //swal("Your file has been updated successfully!", "success")
                            swal("Good job!", "Your file has been updated successfully!", "success")

                        }
                    });
                }
            };
            xhr.onerror = function () {
                alert("Could not upload file.");
            };
            xhr.send(file);
        }
        //            /*
        //                Function to get the temporary signed request from the app.
        //                If request successful, continue to upload the file using this signed
        //                request.
        //            */
        function get_signed_request(file, type) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "/sign_s3?file_name=" + username + "/" + file.name + "&file_type=" + file.type);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        upload_file(file, response.signed_request, response.url, type);
                    } else {
                        alert("Could not get signed URL.");
                    }
                }
            };
            xhr.send();
        }
        //
        //            /*
        //               Function called when file input updated. If there is a file selected, then
        //               start upload procedure by asking for a signed request from the app.
        //            */
        function init_upload(filetype) {
            console.log("here");
            if (filetype == "nid-upload") {
                var nid_files = document.getElementById("national-card").files;
                var nid_file = nid_files[0];
                if (nid_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(nid_file, "nid");
            }
            if (filetype == "pass-upload") {
                var pass_files = document.getElementById("passport-card").files;
                var pass_file = pass_files[0];
                if (pass_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(pass_file, "passport");
            }
            if (filetype == "birth-upload") {
                var birth_files = document.getElementById("birth-cirtificate").files;
                var birth_file = birth_files[0];
                if (birth_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(birth_file, "birth");
            }
            if (filetype == "driving-upload") {
                var driving_files = document.getElementById("driving-license").files;
                var driving_file = driving_files[0];
                if (driving_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(driving_file, "driving");
            }
            if (filetype == "vehicle-upload") {
                var vehicle_files = document.getElementById("vehicle-license").files;
                var vehicle_file = vehicle_files[0];
                if (vehicle_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(vehicle_file, "vehicle");
            }
            if (filetype == "propic-upload") {
                var profile_files = document.getElementById("profile-pic").files;
                var profile_file = profile_files[0];
                if (profile_file == null) {
                    alert("No file selected.");
                }
                get_signed_request(profile_file, "propic");
            }
        }
        $(".save").mouseup(function () {


            $('.loadingcustom').css({
                display: 'block',
                //zindex: 1,
                position: 'fixed',
                width: '200vw',
                //  top: '450px'
            });
            console.log("clicked");
            var toupload = ($(this).attr("id"));
            toupload.replace(/\s+/g, "");
            init_upload(toupload);

        });
        /*     $(function () {
            $(":file").change(function () {
                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });

*/

        function imageIsLoaded(e) {

        };
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用HTML和javascript在许多HTML页面上显示个人资料图片 - display of profile picture on many pages of HTML using HTML and javascript 使用JavaScript SDK从Facebook图形API获取个人资料图片 - Get profile picture from facebook graph api using javascript SDK 使用JavaScript和REST API检索LinkedIn个人资料图片 - Retrieve LinkedIn Profile Picture Using JavaScript with REST API 上传文件前使用 JavaScript 显示预览图片 - Show a preview picture using JavaScript before uploading files 使用 html 中的图像托管服务中的图像上传个人资料图片的图像 - Uploading images for profile picture using images from image hosting service in html 如何使用 javascript 在 Liferay 中检索用户资料图片 - How to retrieve a user profile picture in Liferay with javascript 使用JavaScript将Facebook个人资料图片(从Facebook API获取)保存为文件对象 - Saving Facebook profile picture (fetched from Facebook API) as file object using javascript 如何使用Javascript SDK V2.0获取Facebook用户朋友的头像 - How to get Facebook user's friends' profile picture using Javascript SDK V2.0 使用Facebook Graph API上传个人资料图片 - Profile Picture Upload using Facebook Graph API 使用javascript上传图片 - uploading image using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM