某些文件的进度栏无法加载(javascript)

时间:2018-10-16 20:28:53

标签: javascript jquery ajax

这是我的问题。

我有一个输入,可以同时上传多个文件,然后有一个ajax,它负责发送请求和事件侦听器以加载小节。

问题是,当我上传8个文件时,其中一些不符合验证要求(大小和格式),然后绘制大多数条形而最后一个条形不正确。

文件已上传,但条形图或文本均未绘制

Upload screen

这是JavaScript代码

<script type="text/javascript">
    var newFileList = [];
    $('.addfiles').on('click', function () { $('#fileUploader').click(); return false; });
    $(document).ready(function () {
        $('input[type=file]').change(function () {
            if (this.files.length != 0) { $("#btnUpload").attr('disabled', false); };
            $("#bars").remove();
            $("#divFiles").append('<div id="bars"></div>')
            for (var i = 0; i < this.files.length; i++) { //Progress bar and status label's for each file genarate dynamically
                var fileId = i;
                const file = this.files[i];
                if (validateFileExtension(file)) {
                    $("#bars").append(
                        '<div id = "' + fileId + '" >' +
                        '<div>' + file.name + '</div>' +
                        '<div class="progress">' +
                        '<div class="bar" id="progressbar_' + fileId + '" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>' +
                        ' </div>' +
                        '<div>' +
                        '<input type="button" class="btn btn-danger" style="display:none;line-height:6px;height:25px" id="cancel_' + fileId + '" value="cancel">' +
                        '</div>' +
                        '<div>' +
                        '<p class="progress-status" style="text-align: right;margin-right:-15px;font-weight:bold;color:saddlebrown" id="status_' + fileId + '"></p>' +
                        '</div>' +
                        '<div>' +
                        '<p id="notify_' + fileId + '" style="text-align: right;"></p>' +
                        '</div>' +
                        '</div>'
                    );
                }
            };
            $('file_count').text('# Files selected: ' + newFileList.length);


        })
    });
    function uploadFiles() {
        var file = document.getElementById("fileUploader")//All files
        for (var i = 0; i < newFileList.length; i++) {
            uploadSingleFile(newFileList[i], i);
        }
    }
    function uploadSingleFile(file, i) {
        var fileId = i;
        var ajax = new XMLHttpRequest();
        //Progress Listener
        ajax.upload.addEventListener("progress", function (e) {
            console.log(file);
            var percent = (e.loaded / e.total) * 100;
            $("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
            $('#progressbar_' + fileId).css("width", percent + "%")
            $("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
        }, false);
        //Load Listener
        ajax.addEventListener("load", function (e) {
            $("#status_" + fileId).text("File upload!");
            $('#progressbar_' + fileId).css("width", "100%")

            //Hide cancel button
            var _cancel = $('#cancel_' + fileId);
            _cancel.hide();
        }, false);
        //Error Listener
        ajax.addEventListener("error", function (e) {
            $("#status_" + fileId).text("Upload Failed");
        }, false);
        //Abort Listener
        ajax.addEventListener("abort", function (e) {
            $("#status_" + fileId).text("Upload Aborted");
        }, false);

        var imagePath = window.location.search;
        var filePath = imagePath.replace("imagePath", "filePath");
        ajax.open("POST", "/File"+filePath); // Your API .net, php

        var uploaderForm = new FormData(); // Create new FormData
        uploaderForm.append("file", file); // append the next file for upload
        ajax.send(uploaderForm);

        //Cancel button
        var _cancel = $('#cancel_' + fileId);
        _cancel.show();

        _cancel.on('click', function () {
            ajax.abort();
        })
    }

    function validateFileExtension(file) {

            if (!/(\.bmp|\.jpg|\.gif|\.png)$/i.test(file.name)) {
                bootbox.alert("Invalid file type:" + file.name + " . Only JPG, GIF, PNG or BMP File");
                return false;
            }       
        // Validate Size
        var imgsize = document.getElementById('ImgSize').value;
            var size = file.size;
            // check file size
            if (size > imgsize) {
                $(this).val("");
                bootbox.alert("The size of  " + file.name + "  is too big:  " + size + " Byte, you only can upload " + imgsize + " Byte");
                return false;
        }
        newFileList.push(file);
        return true;
    }
</script>

编辑

应用更改,但遇到与上载文件相同的问题,但是没有在屏幕或其他任何地方绘制条形图

function uploadFiles() {
     filesToUpload = newFileList.slice(0);

     uploadSingleFile(filesToUpload.pop(), 0); // start the process here
}
function uploadSingleFile(file, i) {
    var fileId = i;
    var ajax = new XMLHttpRequest();
    //Progress Listener
    ajax.upload.addEventListener("progress", function (e) {
        var percent = (e.loaded / e.total) * 100;
        $("#status_" + fileId).text(Math.round(percent) + "% uploaded, please wait...");
        $('#progressbar_' + fileId).css("width", percent + "%")
        $("#notify_" + fileId).text("Uploaded " + (e.loaded) + " KB of " + (e.total) + " KB ");
    }, false);
    //Load Listener
    ajax.addEventListener("load", function (e) {
        $("#status_" + fileId).text("File upload!");
        $('#progressbar_' + fileId).css("width", "100%")

        //Hide cancel button
        var _cancel = $('#cancel_' + fileId);
        _cancel.hide();
    }, false);
    //Error Listener
    ajax.addEventListener("error", function (e) {
        $("#status_" + fileId).text("Upload Failed");
    }, false);
    //Abort Listener
    ajax.addEventListener("abort", function (e) {
        $("#status_" + fileId).text("Upload Aborted");
    }, false);

    var imagePath = window.location.search;
    var filePath = imagePath.replace("imagePath", "filePath");
    ajax.open("POST", "/File" + filePath); // Your API .net, php

    var uploaderForm = new FormData(); // Create new FormData
    uploaderForm.append("file", file); // append the next file for upload
    ajax.send(uploaderForm);
    ajax.onreadystatechange = function () {
        if (ajax.readyState === 4) {
            if (ajax.status === 200) {
                console.log('successful');
                if (filesToUpload.length > 0) { // do this inside your ajax success call
                    uploadSingleFile(filesToUpload.pop(), ++i);                      
                }
                else {
                    console.log(ajax.status);
                    console.log('failed');
                }
            }
        }
    }

        //Cancel button
        var _cancel = $('#cancel_' + fileId);
        _cancel.show();

        _cancel.on('click', function () {
            ajax.abort();
        })

}

0 个答案:

没有答案