html5 FormData multipart upload to Django backend - 11 May 2013



As of Chrome 7, Firefox 4, IE 10, Opera 12, and Safari 5 - it is quite possible to programmatically upload file data. https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData#Browser_compatibility

From SBObj.js:

this.PUT = function(theData, theDataContentType) {
    theDataContentType = this.getDefault(theDataContentType, "text/plain");
    var aBlob = new Blob([ theData ], {
        type: theDataContentType
    var aFormData = new FormData();
    aFormData.append("file", aBlob);
    var aDataObj = {
        "type": false,
        "content": aFormData
    private_SendDataObj(private_METHOD_POST, aDataObj);

Where private_SendDataObj is essentially a wrapper for xhr.send(aDataObj.content);. Be sure that there are NO setRequestHeader method calls on the xhr object; even though the Django: File Uploads documentation tells you otherwise.

Django's request.FILES

Google App Engine with django-nonrel to be specific, we can pull in the file data.

From storagebin/init.py and storagebin/internal/blobstore.py:

elif request.method == 'POST':
    if request.FILES and len(request.FILES) == 1:
        uploaded_file = request.FILES['file']
        # write new data
        file_name = files.blobstore.create(uploaded_file.content_type)
        with files.open(file_name, 'a') as f:

refs: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.FILES, https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.UploadedFile, https://developers.google.com/appengine/docs/python/blobstore/overview#Writing_Files_to_the_Blobstore

174 words. Post tags: html5, FormData, multipart, JavaScript, and Django.

Post content is written by Jason Zerbe and licensed CC BY-NC 3.0.