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

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

user1700
1#
user1700 Published in July 18, 2018, 4:58 am

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.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO