Madhu Billy Madhu Billy - 1 month ago 18
Ajax Question

How to send a file using AJAX call without form data

I need to send a PDF file from ajax to call to Django server, without form data

Answer

You can send your files as raw file buffer as follows:

var input = $('#input');

input.change(function(event) {
  var file = this.files[0];
  if (!file) return;

  return $.ajax({
    url: '/django-route', // your route to process the file
    type: 'POST', //
    data: file,
    processData: false,
    contentType: 'application/octet-stream', // set Content-Type header
    success: function(respnse) {
      // do something
    },
    error: function(xhr, textStatus, errorThrown) {
      // do something else
    }
  });
});

If you need to track the progress of your file upload, add the xhr to $.ajax() options:

xhr: function() {
  var xhr = new window.XMLHttpRequest();
  xhr.upload.addEventListener('progress', function(event) {
    if (event.lengthComputable) {
      var progress = Math.floor(10000 * event.loaded / event.total) / 10000;
      console.log(progress); // 0.2536 (25.36%)
    }
  }, false);
  xhr.addEventListener('progress', function(event) {
    if (event.lengthComputable) {
      var progress = Math.floor(10000 * event.loaded / event.total) / 10000;
      console.log(progress);
    }
  }, false);
  return xhr;
}