Home CSRF token missing or incorrect when trying to upload a file with ajax
Reply: 1

CSRF token missing or incorrect when trying to upload a file with ajax

davidb
1#
davidb Published in 2017-12-07 22:52:58Z

I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Here's the upload form:

<form class="uploadForm" method="post" enctype="multipart/form-data">
   {% csrf_token %}
   <input type="file" id="uploadFile">
   <input type="submit" class="button" id="uploadButton" value="Upload">
</form>

Here's my Jquery + Ajax:

$('.uploadForm').on('submit', function(event){
  event.preventDefault();
  var fileSize = ($('#uploadFile')[0].files[0].size/1024);
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);
  var fileData = new FormData($('#uploadFile').get(0));
  $.ajax({
    url: '{% url 'project:uploadFile' %}',
    type: 'post',
    data: {
      'uploadedFile': fileData,
      'fileSize': realSize,
       csrfmiddlewaretoken: '{{ csrf_token }}'
     },
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
  });
});

And in views.py I have this:

class uploadFile(TemplateView):
template_name = "project/uploadFile.html"

def post(self, request):
    fileSize = request.POST.get('fileSize')
    return JsonResponse(fileSize, safe=False)

With the above code I get Forbidden (CSRF token missing or incorrect.) error. I googled this and someone here suggested removing processData and ProcessType. When I remove those two parameters absolutely nothing happens when I submit the form(nothing in the console neither). What could be wrong with this?

Thanks.

Magnus
2#
Magnus Reply to 2017-12-07 23:00:59Z

As per the Django documentation, there is a block of code you need to set ajax up with csrf token. Here is the documentation and the block of code that sets it up.

 //Syntax to run this function once when page loads
    $(function () {
        //You need this CSRF block for ajax calls to work 
        var csrftoken = $.cookie('csrftoken');
        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });
        ///End CSRF block
    });

So put that in and remove the crsf token from the ajax call.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334363 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO