我有一个 Symfony使用 AngularJS 的应用程序在前端通过 POST
方法使用 ajax 上传文件。
工作 POST 方法
数据被添加为 FormData
并且一些 angular.identity
魔法被用来自动填充正确的 application/x-www-form-urlencoded; charset=UTF-8
内容类型:
$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
});
};
这按预期工作,允许我访问我的 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
}
失败的 PUT 方法
但是,当我使用 PUT
方法执行完全相同的操作时,我得到了 200
成功,但没有可访问的数据:
$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
}
问题是为什么 PUT
而不是 POST
会发生这种情况,我该如何解决这个问题?我也可以使用 POST
来更新文件,但这是一个我想避免的 hacky 解决方案。
在使用 PUT
时也有类似的问题,但没有解决问题的适当解决方案:
Send file using PUT method Angularjs
最佳答案
进一步研究后发现这是一个核心 PHP 问题,而不是 AngularJS 或 Symfony 中的错误。
问题是 PHP PUT 和 PATCH 不解析请求,因此内容根本不可用。 (您可以在此处阅读更多信息:https://bugs.php.net/bug.php?id=55815)
解决这个问题的方法是使用 POST
方法,但将该方法伪装成 PATCH/PUT
的方法,如下所示:
$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
});
};
关于javascript - AngularJS put方法上传文件没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723242/