使用Javascript上传个人资料图片

时间:2015-11-17 07:15:02

标签: javascript mongodb image-uploading

我想从用户端上传我的项目的个人资料图片。

我的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>

用于上传文件的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);

            });
    });

我将此文件上传到MongoDB。 我的要求是为特定用户上传图片。

1 个答案:

答案 0 :(得分:2)

是的!我可以做到。想和你分享我的代码:)这段代码用于上传文件和更新上传的文件。

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