【问题标题】:Angular/PHP: upload file data in $_POST, not $_FILESAngular/PHP:在 $_POST 中上传文件数据,而不是 $_FILES
【发布时间】:2017-06-10 19:17:10
【问题描述】:

我在 Debian 上使用 AngularJS v1.6.1, Apache 2.4.10 和 PHP 5.6.24,我正在尝试使用$http POST 服务将文件上传到我的服务器。 在我的php.ini 上,最大文件大小设置为 8Mo,最大帖子大小也是,上传文件已打开,内存大小限制设置为 128Mo。

表格:

<input type="file" accept="application/pdf" id="uploadOT" max-files="1" ng-model="uploadOT" name="uploadOT" valid-file required ng-class="{'md-input-invalid':uploadForm.uploadOT.$error.validFile}" />

Angular 指令:(当输入内容发生变化时,获取 FileReader 对象并发送文件)

myModule.directive('validFile', function() {
    return {
        require:    'ngModel',
        link:       function(scope, elt, attrs, ctrl) {
            ctrl.$setValidity('validFile', elt.val() !== '');
            elt.bind('change', function() {

                var file = document.getElementById('uploadOT').files;
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.sendFile(reader, scope.id);
                };
                scope.showUploadProgress = true;
                scope.filename = file[0].name;
                reader.readAsBinaryString(file[0]);

                ctrl.$setValidity('validFile', elt.val() !== '');
                scope.$apply(function() {
                    ctrl.$setViewValue(elt.val());
                    ctrl.$render();
                });
            });
        }
    };
});

控制器内部:

$scope.sendFile = function(reader, id) {
    var fd = new FormData();
    fd.append('id', id);
    fd.append('file', reader.result);
    fd.append('MAX_FILE_SIZE', 8 * 1024 * 1024);
    $http.post('api/upload.php', fd, {
        headers:            {'Content-Type' : undefined },
        transformRequest:   angular.identity
    }).then(function() {
        alert('upload success');
    }, function() {
        $scope.showUploadError = true;
        $scope.showUploadProgress = false;
        $scope.postError = 'Une erreur inconnue est survenue !';
    });
};

在服务器端(文件api/upload.php),我使用print_r() 打印变量$_POST 和$_FILES。

为什么$_FILES总是空的,而我的文件数据在$_POST['file']?

我可以使用 php 函数 file_put_contents() 从 $_POST['file'] 数据创建文件,但我无法进行可以使用 $_FILES 进行的验证。真的很重要吗(安全问题)?

如果我将我的 POST Content-Type 更改为 multipart/form-data,同样的事情也会发生。

【问题讨论】:

标签: php angularjs forms post


【解决方案1】:

我猜是因为您忘记指定表单元素的编码类型。

enctype="multipart/form-data"

因此,默认 - 浏览器将假定表单编码类型为“application/x-www-form-urlencoded”,它不支持此文件大大地。您仍然可以使用股票编码方法安全地发送文件二进制数据,但这可能是性能和功能决定您选择的因素的地方。我建议运行一些测试来确认哪个是最快的。在某些情况下,差异可以忽略不计,并且可能是为了保持一致性。

【讨论】:

  • 当我显示我的标头时,请求是 Content-Type multipart/form-data,并且请求的数据正确编码...不是 application/x-www-form-urlencoded.. .
  • 尝试添加它,并将method="post" 也添加到元素中。然后 vardump $_FILES。编辑:另外,检查您的 php ini 以确保“file_uploads”已打开。
  • 你的 ini 中的“file_uploads”选项怎么样?
  • 正如我在问题中所说,file_uploads 是“开启”
  • 啊,是的,对不起。你能告诉我整个帖子表格(或至少输入)吗?
【解决方案2】:

跳过 FileReader API,直接使用file 对象:

<input type=file files-input ng-model="files" ng-change="upload()" />

filesInput 指令

angular.module("myApp").directive("filesInput", function() {
  return {
    require: 'ngModel',
    link: function linkFn (scope, elem, attrs, ngModel) {
      elem.on("change", function (e) {
        ngModel.$setViewValue(elem[0].files, "change");
      });
    },
  };
});

upload() 函数

 vm.upload = function() {

    //var formData = new $window.FormData();
    //formData.append("file-0", vm.files[0]);

    var config = { headers: { "Content-Type": undefined } };

    $http.post(url, vm.files[0], config)
    .then(function(response) {
      vm.result = "SUCCESS";
    }).catch(function(response) {
      vm.result = "ERROR "+response.status;
    });
  };

XHR API send() 方法可以发布file 对象或FormData 对象。直接发送 file 对象效率更高,因为 XHR API 使用 base64 encoding 来处理具有 33% 开销的 FormData 对象。

DEMO on PLNKR.

【讨论】:

  • 你能告诉我你的变量 vm 来自哪里吗?如果我有其他值要发送,我想我必须使用 FormData?
【解决方案3】:

为了使其正常工作,我必须进行以下修改:

指令:

myModule.directive('validFile', function() {
    return {
        require:    'ngModel',
        link:       function(scope, elt, attrs, ctrl) {
            ctrl.$setValidity('validFile', elt.val() !== '');
            elt.bind('change', function() {

                var file = document.getElementById('uploadOT').files;
                var reader = new FileReader();
                reader.onload = function(e) {
                    scope.sendFile(file[0], scope.OT);  ////CHANGE HERE
                };
                scope.showUploadProgress = true;
                scope.filename = file[0].name;
                reader.readAsArrayBuffer(file[0]);      ////CHANGE HERE

                ctrl.$setValidity('validFile', elt.val() !== '');
                scope.$apply(function() {
                    ctrl.$setViewValue(elt.val());
                    ctrl.$render();
                });
            });
        }
    };
});

控制器内部

$scope.sendFile = function(file, id) {
        var fd = new FormData();
        fd.append('id', id);
        fd.append('file', file);
        fd.append('MAX_FILE_SIZE', 8 * 1024 * 1024);
        $http({
            method: 'POST',
            url: 'upload.php',
            data: fd,
            headers: {'Content-Type': undefined, 'Process-Data': false},
            transformRequest: angular.identity
        }).then( function() {
            console.log('success');
        }, function() {
            console.log('failure');
        });
    };

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 2011-04-23
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2011-08-06
    • 1970-01-01
    相关资源
    最近更新 更多