如何取消/中止jQuery AJAX文件上传

时间:2018-04-02 12:30:27

标签: javascript jquery ajax file-upload jquery-file-upload

我使用Ajax文件上传功能,状态栏位于模态中。代码工作正常。但是当用户点击取消按钮(上传时)时,模态已关闭,但文件正在后台上传到服务器。

我尝试xhr.abort();功能取消上传。但它不起作用。如何在用户单击取消按钮时停止文件上载过程。

我正在使用jquery 1.10.2版本。

$(function () {
        $('#showonlyvalue-portvid').hide();
        $('#btnuploadvideo').click(function () {
            if (jQuery("#verifyvideo-file").valid()) {
                $('.myprogress').css('width', '0');
                $('.successmsgfile-video').text('');
                var formData = new FormData();
                formData.append('portfoliovideos', $('input[name=portfoliovideos]')[0].files[0]);
                $('#showonlyvalue-portvid').show();
                $('#btnuploadvideo').attr('disabled', 'disabled');
                $('.successmsgfile-video').text('Uploading in progress...');
                $.ajax({
                    url: "<?php echo base_url(); ?>profile/port_videoone"
                    , data: formData
                    , processData: false
                    , contentType: false
                    , type: 'POST' // this part is progress bar
                    , xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    }
                    , success: function (data) {
                        console.log(data);
                        $('#upload-video-file').modal('hide');
                        swal("Success!", "Video has been uploaded!", "success");
                        $('#showonlyvalue-portvid').hide();
                        $('.myprogress').css('width', '0');
                        $('.successmsgfile-video').text('');
                        $('#btnuploadvideo').prop('disabled', false);
                        $('input.form-control').val('');
                        $("#verifyvideo-file")[0].reset();
                    }
                });
            }
        });
    });
$(document).on('click','.stopvideo', function(e){
    xhr.abort();
    xhr = null;
    console.log("Canceled");
});


<div id="upload-video-file" class="modal fade" tabindex="-1">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header"></div>
            <div class="modal-body">
                <form id="verifyvideo-file" method="post" class="padbtm20">
                    <div class="form-group width100 hirehide nomargin dispinline">
                        <input type="file" id="portvideoname" name="portfoliovideos" accept="video/mp4,video/x-m4v,video/ogv,video/webm,video/quicktime" required>
                    </div>
                    <div class="form-group" id="showonlyvalue-portvid">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>
                        <div class="successmsgfile-video"></div>
                    </div>
                    <div class="form-group margin18 dispinline">
                        <input type="button" id="btnuploadvideo" class="btn btn-primary" value="Upload" />
                        <button type="button" class="btn btn-default stopvideo">Cancel</button>
                    </div>
                </form>
            </div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

控制台是否显示任何错误?我认为这可能是因为xhr变量超出了范围。尝试将该点击监听器放在xhr声明下面。

答案 1 :(得分:1)

尝试使用全局变量并在其上调用.abort()

var ajaxCall;

$(function () {
        $('#showonlyvalue-portvid').hide();
        $('#btnuploadvideo').click(function () {
            if (jQuery("#verifyvideo-file").valid()) {
                $('.myprogress').css('width', '0');
                $('.successmsgfile-video').text('');
                var formData = new FormData();
                formData.append('portfoliovideos', $('input[name=portfoliovideos]')[0].files[0]);
                $('#showonlyvalue-portvid').show();
                $('#btnuploadvideo').attr('disabled', 'disabled');
                $('.successmsgfile-video').text('Uploading in progress...');
                ajaxCall = $.ajax({
                    url: "<?php echo base_url(); ?>profile/port_videoone"
                    , data: formData
                    , processData: false
                    , contentType: false
                    , type: 'POST' // this part is progress bar
                    , xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    }
                    , success: function (data) {
                        console.log(data);
                        $('#upload-video-file').modal('hide');
                        swal("Success!", "Video has been uploaded!", "success");
                        $('#showonlyvalue-portvid').hide();
                        $('.myprogress').css('width', '0');
                        $('.successmsgfile-video').text('');
                        $('#btnuploadvideo').prop('disabled', false);
                        $('input.form-control').val('');
                        $("#verifyvideo-file")[0].reset();
                    }
                });
            }
        });
    });
$(document).on('click','.stopvideo', function(e){
    ajaxCall.abort();
    console.log("Canceled");
});


<div id="upload-video-file" class="modal fade" tabindex="-1">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header"></div>
            <div class="modal-body">
                <form id="verifyvideo-file" method="post" class="padbtm20">
                    <div class="form-group width100 hirehide nomargin dispinline">
                        <input type="file" id="portvideoname" name="portfoliovideos" accept="video/mp4,video/x-m4v,video/ogv,video/webm,video/quicktime" required>
                    </div>
                    <div class="form-group" id="showonlyvalue-portvid">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>
                        <div class="successmsgfile-video"></div>
                    </div>
                    <div class="form-group margin18 dispinline">
                        <input type="button" id="btnuploadvideo" class="btn btn-primary" value="Upload" />
                        <button type="button" class="btn btn-default stopvideo">Cancel</button>
                    </div>
                </form>
            </div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>

让我知道