In the last post, I just added the entities in the database, but did not bind the meta data with eBook files. This post will demonstrate how to upload the file in AJAX flavor:

The idea is inspired by this tutorial , using dojo.io.iframe, we could submit a form with file upload asynchronously. In client side, a hidden field meta is added to store the marshaled JSON string. dojo.io.iframe.send shares the same defer concept as dojo.xhrPost:

var meta = dojo.query("input[@name=meta]", form)[0];
    meta.value = dojo.toJson(cache[i]);

    // submit the form
    dojo.io.iframe.send({
        url: form.action,
        method: "post",
        handleAs: "json",
        form: form,
    }).addCallback(function(ret) {
    … …

NOTE: the handleAs is json, so the argument ret is JavaScript object.

In server side, the JSON string needs to be wrapped by textarea, this is the hard requirement of dojo.iframe.send.

return HttpResponse("<textarea>%s</textarea>" % simplejson.dumps(retset) , mimetype=‘text/html’);

Conceptually, add-by-search will issue INSERT operation to the database, the result may fall in the following categories:

  • Success
  • FileAlreadyExist: the eBook file exists, so the uploaded file is discarded
  • UnexpectedError: an 500 error happens in server side for unknown reason.

Check r34 for the implementation.

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks

2 Comments to “Learning Django by Example(6): AJAX File Upload”

  1. anthony | June 29th, 2009 at 2:49 am

    Well I have now rolled it out and working with an AJAX engine for a front end. What I would like to turn off is the requirement for having to be logged in, as this requires the user to be registered. Not something that I think is applicable to my site.

    As you may have noticed in other posts I am using the YUI AJAX framework and I would recommend it to anyone that is using Django as an AJAX framework.
    http://www.casinoexperte.eu

  2. ian | February 17th, 2010 at 8:36 am

    I’m trying to implement something similar to this at http://zedindustries.com but have not been able to get it working correctly yet.

Leave a Comment