Search code examples
ajaxdjangodjango-formsdjango-file-upload

Submitting files to django server from outside via Ajax


From client side A, I want to create a file on the fly by javascript and send it to a Django server B via Ajax for further processing.

The javascript code in A is like below. I use blob to create a file without a real uploaded one and send it via Ajax.

console.log("start sending binary data...");
var form = new FormData();
var blob = new Blob([bytesArray], {type: 'example/binary'});    
form.append('file_name', blob, 'test.bin');    

$.ajax({
   url: THIRD_SERVER + 'test_binary',
   type: 'POST',       
   data: form,
   processData: false,
   success: function(data){
      console.log('test_binary ' + JSON.stringify(data));
   }
});

However, on the Django server, what I got is like this (when i print request.POST), hence when i used Django FileUpload, it returned an exception.

<QueryDict: {u' name': [u'"file_name"'], u'------WebKitFormBoundarybCp3z7mAduz8BBDq\r\nContent-Disposition: form-data': [u''], u' filename': [u'"test.bin"\r\nContent-Type: example/binary\r\n\r\n\ufffd\ufffd\ufffd\x01\x05\x06\r\n------WebKitFormBoundarybCp3z7mAduz8BBDq--\r\n']}>

So I guess the above javascript doesn't do the right thing to send file to a Django server. Is there any proper way that I can use the FileUpload to handle?

Thanks,


Solution

  • You have to tell $.ajax not to set a content type otherwise it will be set incorrectly

    $.ajax({
       url: THIRD_SERVER + 'test_binary',
       type: 'POST',       
       data: form,
       processData: false,
       contentType: false,
       success: function(data){
          console.log('test_binary ' + JSON.stringify(data));
       }
    });