henrikstroem
henrikstroem

Reputation: 3068

Blueimp fileupload() callbacks not called

I am using Blueimp fileupload() to post image files to a django-tastypie API.

The code below works correctly as far as the file is being uploaded:

        $("#image").fileupload({
            dataType: 'json',
            start: function() {
                console.log("start fileupload");
            },
            progress: function(e, data) {
                console.log(data.loaded + " " + data.total);
            },
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
            },
            done: function(e, data) {
                console.log("done uploading file.");
            }                   
        });

        $("#image").bind('fileuploadfinished', function (e, data) {
            console.log("fileuploadfinished");
        });

However, the done callback is never called. I tried binding the fileuploadfinished and that is also never called.

start and progress are both called as expected.

beforeSend is undocumented, but is needed by django-tastypie for SessionAuthentication - removing it doesn't change that done and fileuploadfinished is never called.

Upvotes: 1

Views: 3781

Answers (2)

Wim Stockman
Wim Stockman

Reputation: 59

I was having the same problem. it is because you set your datatype 'json'. Just leave this out or put it to plain and it will work. Your server , or uploadhandler isn't return a json answer.

Upvotes: 2

henrikstroem
henrikstroem

Reputation: 3068

As it turns out, django-tastypie correctly returns a 201 status code. However, this status code is not considered a success by fileupload.

This code handles the status code manually:

    $("#image").fileupload({
        dataType: 'json',
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        },
        complete: function(xhr) {
            if (xhr.readyState == 4) {
                if (xhr.status == 201) {
                    console.log("Created");
                }
            } else {
                console.log("NoGood");
            }
        },
    });

That means, the complete callback is called whether success or failure, and checking the readyState and status together can tell whether it succeeded.

There are some other ways to get this to work, however I think this is the best. More details here:

Data inserted successful but jquery still returning error

Upvotes: 6

Related Questions