1

I have a Symfony application that uses AngularJS on the front-end to upload files with ajax via the POST method.

Working POST Method

The data is added as FormData and some angular.identity magic is used to auto populate the correct application/x-www-form-urlencoded; charset=UTF-8 content-type:

$scope.fileUpload = function (file) {
    var fd = new FormData();
    fd.append("title", file.title);
    fd.append("file", $scope.file);

    $http.post('example/upload', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then({
        // do something
    });
};

This works as expected allowing me to access the posted variables in my controller:

// Expects data from a post method
public function postFile(Request $request)
{
    $title = $request->get('title');
    /** @var $file UploadedFile */
    $file = $request->files->get('file');

    // data success, all is good
}

Failing PUT Method

However when I do exactly the same using the PUT method, I get a 200 success but there is no accessible data:

$scope.fileUpload = function (file) {
    var fd = new FormData();
    fd.append("title", file.title);
    fd.append("file", $scope.file);

    $http.put('example/update', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then({
        // do something
    });
};


// Expects data from a put method
public function putFile(Request $request)
{
    $title = $request->get('title');
    /** @var $file UploadedFile */
    $file = $request->files->get('file');

    // the request parameters and query are empty, there is no accessible data
}

AngularJS put body is empty

The question is why does this occur with PUT but not POST and how can I get around this? I could use POST to update the file too but that's a hacky solution I'd like to avoid.

There are similar questions but no appropriate solutions that fix the issue whilst using PUT:

Send file using PUT method Angularjs

AngularJS image upload with PUT, possible, how?

Angularjs file upload in put method not working

Dan
  • 11,914
  • 14
  • 49
  • 112

1 Answers1

2

After delving further into this it appears this is a core PHP issue rather than a bug in AngularJS or Symfony.

The issue is that PHP PUT and PATCH do not parse the request so the content simply isn't available. (You can read more here: https://bugs.php.net/bug.php?id=55815)

A workaround to this is using the POST method but spoofing the method to be that of PATCH/PUT like so:

$scope.fileUpload = function (file) {
    var fd = new FormData();
    fd.append("title", file.title);
    fd.append("file", $scope.file);
    fd.append('_method', 'PUT');

    $http.post('example/update', fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then({
        // do something
    });
};
Dan
  • 11,914
  • 14
  • 49
  • 112