Jquery文件上传进度条

时间:2017-03-16 05:43:29

标签: javascript php jquery ajax zend-framework2

我使用jquery ajax上传带有进度条的视频和图像文件。我正在使用服务器端表单验证并检查重复条目。我的问题是进度条完成后显示验证错误消息。我想要这样的东西......

if form validation is correct
    then show progress bar
else if form validation is not correct
    then only show error message of form validation
else if duplicate entry
    then only show error message of duplicate entry

这是我的js代码:

$.ajax({
    url:         ajaxUrl,
    type:        'POST',
    dataType:    'json',
    processData: false,
    contentType: false,
    async:       true,
    data: formData,
    xhr: function () {
        //upload Progress
        var xhr = $.ajaxSettings.xhr();

        if (xhr.upload) {
            xhr.upload.addEventListener('progress', function (event) {
                var percent = 0;
                var position = event.loaded || event.position;
                var total = event.total;

                if (event.lengthComputable) {
                    percent = Math.ceil(position / total * 100);
                }
                var temp = event.loaded/event.total*100;

                //update progressbar
                $('div#upload-progress').text(percent + "%");
                $('div#upload-progress').css("width",  + temp + "%");

            }, true);
        }
        return xhr;
    },
    complete: function(xhr) {
        if(xhr.responseText) {
            //console.log(xhr);
        }
    },
    success: function(data, status){
        if (data.hasOwnProperty('form-error')) {
            $.each(data['form-error'], function (key, value) {  
                $("span#span_" + key).text(value);
            })
        } else {
            // Form validation is correct
        }               
    },
    error : function(xhr, textStatus, errorThrown) {
        var data = xhr.responseText;
        myWindow = window.open("data:text/html," + encodeURIComponent(data), "parent", "width=1000, height=600");
        myWindow.focus();       
    }
});

任何人都可以给我任何建议吗?

2 个答案:

答案 0 :(得分:1)

如果您正在使用服务器验证文件,则意味着必须首先上传文件才能对其进行验证,因此您首先要查看进度条。如果您只想检查重复项(基于文件名,大小等),则需要2个ajax请求:

  1. 仅发送文件名&大小并验证它。

  2. 如果有效,请上传文件。 (当然,再次验证)

  3. 只需2美分。

答案 1 :(得分:0)

我确实上传了带进度条的AJAX文件,您可能想看看?我猜? https://github.com/felixfong227/fileupload/blob/master/static/js/index.js

相关问题