JQuery-file-upload: handle server errors

I am trying to implement error handling for blueimp jQuery-File-Upload. It is easy to implement for errors that I can catch on the server and wrap them in a JSON object. But what if there is a PHP error on the server and the message is displayed as a standard PHP message? I tried to process it with a rollback:

jQuery('#fileupload').fileupload({
    fail: function (ev, data) {
        if (data.jqXHR) {
            alert('Server-error:\n\n' + data.jqXHR.responseText); 
        }
    }, 
    otherOptions
});

It works, but the callback also starts if I press the cancel button to delete the image. So I added if when data.jqXHR will be different between server error and clicking cancel button. But then, if the cancel button is pressed, the image is no longer removed from the list.

Any idea how to implement such error handling for unexpected server errors?

Thanks Ben

+4
2

.

.bind('fileuploadfail', function (e, data) {

.

+3

, , . , , .

add: function (e, data) {
        if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) {
            $.each(data.files, function (index, file) {
                // UPLOAD INDICATOR
                // file heading
                single_upload = "<b class='file_upload'>"+file.name+"</b>";
                // cancel btn
                single_upload += "<a class='remove_upload'> || Cancel!</a>";
                // contain
                single_upload = "<div class='upload'>"+single_upload+"</div>";
                // create and display node related to specific upload
                data.context = $(single_upload).appendTo(document.body);

                // CANCEL BTN LISTENER
                $(data.context).find(".remove_upload").click(function() {
                    // prevent displaying of server error
                    // (prevent fileupload "fail" event trigger)
                    fileupload_userCancelledUpload = true;
                    jqXHR.abort();
                    data.context.remove();
                })
            });
            var jqXHR;
            data.process().done(function () {
                jqXHR = data.submit();
            });
        }
    },

fail: function (e, data) {
        if (!fileupload_userCancelledUpload) {
            // catches server errors (not validation errors), such as 413
            handleUploadFailure(data.context, " Server error: "+$(data.jqXHR.responseText).filter("title").text());
        }
        fileupload_userCancelledUpload = false;
    }
+1

Source: https://habr.com/ru/post/1536153/


All Articles