0

I've seen many posts similar to this questions, but I can't find the solution. This is the request in frontend(angularjs).

formData = new FormData();
let blob = dataURLtoBlob(canvas.toDataURL('image/png'));
console.log("blob", blob);
formData.append("cropped_image[]", blob);
formData.append("title", $('#title').val());
console.log($('#title').val());
console.log(formData.has('title'));
console.log(formData.has('cropped_image[]'));
console.log("formData", formData);
var req = {
    method: 'POST',
    url: '/admin/logos/save',
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    data: formData,
    contentType: false,
    cache: false,
    processData: false
}
$http(req).then(function (json) {
    console.log('success');
    console.log(json.data);
    location.href = '/admin/logos';
});

And I've received in laravel backend.

$logo->title = $request->title;
print_r('----------------------------------\n');
print_r($request->all());
count($request->all());
foreach ($request->all() as $x => $value){
    print_r($x);
    print_r('sldf');
    print_r($value);
}
print('-------------');
// $logo->filename = $request->filename;
print_r($request->cropped_image);

I've used several ways to receive, but $request->all() returns empty array(). enter image description here

Please help me.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
thinkmore
  • 229
  • 5
  • 15
  • When posting objects created by the [FormData API](https://developer.mozilla.org/en-US/docs/Web/API/FormData), it is important to set the Content-type header to undefined. – georgeawg Jan 27 '20 at 09:01
  • In request, ```contentType: false``` and ```header{'Content-Type': undefined}``` is different? – thinkmore Jan 27 '20 at 09:13
  • With the AngularJS [$http service](https://docs.angularjs.org/api/ng/service/$http#$http-arguments) the `contentType:` property is ignored. It is often erroneously added by coders who confuse $http with [jQuery.ajax](https://api.jquery.com/jQuery.ajax/) – georgeawg Jan 27 '20 at 15:30

2 Answers2

0

I've solved and the request should be as follows.

var req = {
    method: 'POST',
    url: '/admin/logos/save',
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
        'Content-Type': undefined
    },
    transformRequest: angular.identity,
    data: formData,
    cache: false,
    processData: false
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
thinkmore
  • 229
  • 5
  • 15
-1

You may add dataType: 'json' to your req variable

var req = {
            method: 'POST',
            dataType: 'json',
            url: '/admin/logos/save',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: formData,
            contentType: false,
            cache: false,
            processData: false
}

Then in your controller

dd($request->input->all());
Foued MOUSSI
  • 4,643
  • 3
  • 19
  • 39