Search code examples
jquery-forms-pluginasyncfileupload

How can I cancel a file upload using the jQuery forms plugin


I'm using the jQuery Forms plugin to do an asynchronous file upload. Currently, the only way for the user to abort that upload is to press the "Stop" button on their browser, which may cause other javascript and ajax requests to stop as well. I'd like to provide a cancel button, but I haven't found any way to cancel an upload as it is happening using the API.

Is there a built-in way, or at least a robust hack I can use, to cancel the upload as it occurs?


Solution

  • The ajaxForm method takes all the same options that jQuery.ajax takes, so it is possible to capture the dummy xhr that it produces in a beforeSend handler. The xhr has an abort method that aborts the file upload:

    f.ajaxForm({
        beforeSend: function(xhr) {
            cancelBtn.click(xhr.abort);
        }});