Request object is empty in a lumen api

Viewed 1929

Uploading the image file in lumen API using ajax call, it not getting the image in the lumen for processing, the Request object is empty.

Ajax call

var file = $('#img')[0].files[0];
var form_data = new FormData(document.getElementById("myform"));
form_data.append("img", file);

$.ajax({
    url: "http://localhost:8000/api/image",
    type: "POST",
    data: form_data,
    enctype: 'multipart/form-data',
    processData: false, // tell jQuery not to process the data
    contentType: false   // tell jQuery not to set contentType
})
.done(function (data) {
    console.log(data);
});

Route

$api->post('/image', 'ImagesController@addImage');

Controller

public function addImage(Request $request) {
    return $request; // returns empty object
}

Request payload

Response

2 Answers

You can build a JavaScript object this way, this will ensure passing the body to the request.

let form_data = {
      'name': $('#name').value(),
      'file': $('#img')[0].files[0]
    };

    $.ajax({
      url: "http://localhost:8000/api/image",
      type: "POST",
      data: form_data,
      enctype: 'multipart/form-data',
      processData: false, // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    })
    .done(function (data) {
      console.log(data);
    });
Related