【发布时间】:2019-04-17 08:33:44
【问题描述】:
我有一个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
});
};
这按预期工作,允许我访问控制器中发布的变量:
// 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
【问题讨论】:
标签: javascript php angularjs ajax symfony