javascript - AngularJS put方法上传文件没有数据

标签 javascript php angularjs ajax symfony

我有一个 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
}

AngularJS put body is empty

问题是为什么 PUT 而不是 POST 会发生这种情况,我该如何解决这个问题?我也可以使用 POST 来更新文件,但这是一个我想避免的 hacky 解决方案。

在使用 PUT 时也有类似的问题,但没有解决问题的适当解决方案:

Send file using PUT method Angularjs

AngularJS image upload with PUT, possible, how?

Angularjs file upload in put method not working

最佳答案

进一步研究后发现这是一个核心 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/

相关文章:

javascript - 如何使用 AngularJS Controller 加载 Markdown 文件

javascript - 具有嵌套 json 属性的行

javascript - 为什么在对象字面量定义中使用数组/大括号来允许动态计算 Javascript/ES2015 中的键?

javascript - 如何使用javascript从外部文件加载php vars

php - Jquery注入(inject)html不起作用。 ajax调用不稳定

javascript - AngularJS - 动态添加和删除表中的表单字段

javascript - 如何在 JQuery 中对数据进行排序

javascript - 从数组中删除元素,直到只有 10 个元素

javascript - php 中的 google API javascript 代码

javascript - 在 Developer Console 中获取 AngularJS 的对象和变量列表