【发布时间】: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,同样的事情也会发生。
【问题讨论】:
-
在这篇文章中查看答案:stackoverflow.com/questions/20487212/…
-
@num8er:我没有使用“ng-file-upload”,也无法使用。