Ad

Cancel File Inprogress File Upload Via AjaxForm Plugin

- 1 answer

I am using http://hayageek.com/ajax-file-upload-jquery/ (http://malsup.com/jquery/form/#ajaxForm) plugin to upload files via ajax which is working fine. Now I want to put a file size restriction before file is being uploaded. I tried below highlighted code but that does not cancel file uploading at all.

$('#fileUpload').ajaxForm({
    beforeSend: function () {
        // File size restriction code
        var fileSize = $('.custom-file-input')[0].files[0].size; // in bytes
        fileSize = (fileSize / 1024) / 1024; // MB
        if (fileSize > 2) {
            $('.progress').hide();
            $('input#file').val('');
            $('.custom-file-label').html('<span class="bar-container">Choose file<span class="bar [email protected]"></span></span>');
            parent.setError('Please Upload a file upto 250 mb.');                
            return false;
        }
        // File size restriction code
    },
    uploadProgress: function (event, position, total, percentComplete) {
        // some code
    },
    complete: function (xhr) {
        var result = JSON.parse(xhr.responseText);
        // some code
    },
    url: '/Records/UploadSharedDocuement'
});

Can anyone pls help

Ad

Answer

Abort Ajax on failed condition like this.

$.ajax({
    url : 'myfile',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        var fileSize = $('.custom-file-input')[0].files[0].size;
        if(fileSize>1024)
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('Uploaded');
    }
});
Ad
source: stackoverflow.com
Ad