Upload file and JSON data in the same POST request using jquery ajax?

Viewed 23365

I am trying to send a POST request using jQuery Ajax, where I would like to upload a file and some json data. Please find code,

var logoImg = $('input[name="logoImg"]').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);

var objArr = [];
objArr.push({
  "id": id,
  "name": userName
});

var obj = [{
  "objArr": objArr,
  "formData": formData
}];

$.ajax({
  type: "POST",
  url: url,
  dataType: "json",
  data: JSON.stringify(obj),
  contentType: "application/json",
  cache: false,
  async: false,
  complete: function(data) {
    alert("success");
  }
});

But I am getting Internal server error: 500 and the backend API is not called.

Please help me to send a file and an array obj in same AJAX request. Thanks in advance

2 Answers

Example:-

** let formData = new FormData(); formData.append('file', input.files[0], input.files[0].name);**

$.ajax({
    url: '/yourroute',
    method: 'POST',
    contentType: false,
    processData: false,
    data: formData,
    success: function(res){
        console.log('successfully')
    },
    error: function(){
        console.log('error')
    }
})
Related