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
}
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