【问题标题】:AngularJS put method to upload files gives no dataAngularJS put 方法上传文件没有给出数据
【发布时间】: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

AngularJS image upload with PUT, possible, how?

Angularjs file upload in put method not working

【问题讨论】:

    标签: javascript php angularjs ajax symfony


    【解决方案1】:

    在深入研究之后,这似乎是一个核心 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
        });
    };
    

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 2011-12-17
      • 2013-12-10
      • 2019-06-17
      • 1970-01-01
      • 2016-09-04
      • 2017-11-09
      • 1970-01-01
      • 2014-11-16
      相关资源
      最近更新 更多