简体   繁体   English

如何使用javascript和ajax调用为文件上传添加进度条?

[英]How to add a progress bar to file upload using javascript and ajax call?

I need a progress bar in my file uploader. 我的文件上传器中需要一个进度栏。 This is the ajax call I am using for file upload and progress bar 这是我用于文件上传和进度栏的ajax调用

$(function() {

        $('button[type=button]').click(function(e) {
            e.preventDefault();
            //Disable submit button
            $(this).prop('disabled',true);

            var form = document.forms[0];
            var formData = new FormData(form);

            // Ajax call for file uploaling
            var ajaxReq = $.ajax({
                url : URI.file.multipleFileUploadUrl(),
                type : 'POST',
                data : formData,
                cache : false,
                contentType : false,
                processData : false,
                xhr: function(){
                    //Get XmlHttpRequest object
                     var xhr = $.ajaxSettings.xhr() ;

                    //Set onprogress event handler

                     xhr.upload.onprogress = function(event){
                        var perc = Math.round((event.loaded / event.total) * 100);
                        $('#progressBar').text(perc + '%');
                        $('#progressBar').css('width',perc + '%');
                     };

                     return xhr ;
                },
                beforeSend: function( xhr ) {
                    //Reset alert message and progress bar
                    $('#alertMsg').text('');
                    $('#progressBar').text('');
                    $('#progressBar').css('width','0%');
                }
            });

            // Called on success of file upload
            ajaxReq.done(function(msg) {
                $('#alertMsg').text(msg);
                $('input[type=file]').val('');
                $('button[type=submit]').prop('disabled',false);
            });

            // Called on failure of file upload
            ajaxReq.fail(function(jqXHR) {
                $('#alertMsg').text(jqXHR.responseText+'('+jqXHR.status+
                        ' - '+jqXHR.statusText+')');
                $('button[type=submit]').prop('disabled',false);
            });
        });
    });

Find below is the file upload which works correctly without integrating the progress bar. 在下面找到的是无需集成进度条即可正常工作的文件上传。

function multipleFileUpload(form) {
    var uploadSuccess = true;
    var data = new FormData(form);

    var csrf_headerName  = $("meta[name='_csrf_header']").attr("content");
    var csrf_paramValue  = $("meta[name='_csrf']").attr("content");
    ShowLoad();
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: URI.file.multipleFileUploadUrl(),
        data: data,
        beforeSend: function (request) {
            request.setRequestHeader(csrf_headerName, csrf_paramValue);
        },
         processData: false,
         contentType: false,
         cache: false,
         timeout: 6000000,
         success: function (data) {
            HideLoad();
            data.forEach(function(d, index){
                if(d.status === 'ERROR'){
                    // HideLoad();
                    uploadSuccess = false;
                    toastr.error('Error has occurred while uploading image file '+d.data.name);
                }else if( d.data.id != null ){
                    //HideLoad();
                    //toastr.success('Successfully updated '+d.data.name, 'Upload Success');
                }
            });

            if(uploadSuccess){
                mediaFileMetaDataSave(data[0],data[1]);
            }
         },
         error: function (e) {
            HideLoad();
            toastr.error('Error has occurred while uploading attachments.');
         }
    });
 }

WHen I use the above code in my script I can do file upload properly although the progress bar reach 100% immediately before file upload is complete. 当我在脚本中使用上面的代码时,尽管进度条在文件上传完成之前立即达到100%,但我仍可以正确地上传文件。 What is wrong here? 怎么了

This works fine. 这很好。

function submitForm(form) {
        ShowLoad();
        var data = new FormData(form);
        var csrf_headerName  = $("meta[name='_csrf_header']").attr("content");
        var csrf_paramValue  = $("meta[name='_csrf']").attr("content");

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: URI.file.singleFileUploadUrl(),
        data: data,
        beforeSend: function (request, xhr) {
            request.setRequestHeader(csrf_headerName, csrf_paramValue);
             //Reset alert message and progress bar
            $('#alertMsg').text('');
            $('#progressBar').text('');
            $('#progressBar').css('width','0%');
        },
        processData: false,

        contentType: false,
        cache: false,
        timeout: 6000000,
        success: function (data) {
            HideLoad();
        },

        xhr: function(){
            //Get XmlHttpRequest object
             var xhr = $.ajaxSettings.xhr() ;
            //Set onprogress event handler
             xhr.upload.onprogress = function(data){
                var perc = Math.round((data.loaded / data.total) * 100);
                $('#progressBar').text(perc + '%');
                $('#progressBar').css('width',perc + '%');
             };
             return xhr ;
        },
        error: function (e) {
            HideLoad();
            toastr.error('Error has occurred while uploading the media file.');
        }
    });
 }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM