Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using Ajax on POST?

I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.

# html
<form method="post" id="Form" enctype="multipart/form-data">
  {% csrf_token %} # django security
  <input id="image_file" type="file" name="image_file">
  <input type="submit" value="submit">
</form>

# javascript
$(document).on('submit', '#Form', function(e){
  e.preventDefault();

  var form_data = new FormData();
  form_data.append('file', $('#image_file').get(0).files);

  $.ajax({
      type:'POST',
      url:'my_url',
      processData: false,
      contentType: false,
      data:{
          logo:form_data,
          csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
      },
  });
});

# views.py (server side)
def myFunction(request):
    if request.method == 'POST':
        image_file = request.FILES
        ...
...

I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.

Am I doing something incorrectly?

like image 959
Hiroyuki Nuri Avatar asked Jun 22 '17 19:06

Hiroyuki Nuri


People also ask

Can we upload file using AJAX?

Ajax file uploadsA JavaScript method must be coded to initiate the asynchronous Ajax based file upload; A component must exist on the server to handle the file upload and save the resource locally; The server must send a response to the browser indicating the JavaScript file upload was successful; and.

Does AJAX use Get or Post?

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option.


2 Answers

Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.

If you are using JQuery solely for the use of ajax, then I recommand using axios:

const axios = require('axios');

var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);

axios({
    method: 'post',
    url: 'your_url',
    data: formData,
    headers: {
        "X-CSRFToken": CSRF_TOKEN, # django security
        "content-type": "multipart/form-data"
    }
}).then(function (response) {
    # success
});

Axios Documentation


Jquery/Ajax answer:

var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security

$.ajax({
   url : 'your_url',
   type : 'POST',
   data : formData,
   processData: false,
   contentType: false,
   success : function(data) {
       # success
   }
});

Jquery/Ajax Documentation

like image 186
Hiroyuki Nuri Avatar answered Oct 27 '22 16:10

Hiroyuki Nuri


The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES

Try this:

$(document).on('submit', '#creationOptionsForm', function(e){
  e.preventDefault();

  var form_data = new FormData($('#creationOptionsForm')[0]);
  $.ajax({
      type:'POST',
      url:'/designer/results/',
      processData: false,
      contentType: false,
      async: false,
      cache: false,
      data : form_data,
      success: function(response){

      }
  });
});

Update:

basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.

While cache will force browser to not cache uploaded data to get updated data in ajax request

Official Documentation here

like image 31
Mahesh Singh Chouhan Avatar answered Oct 27 '22 15:10

Mahesh Singh Chouhan