我目前的情况是:我做了嵌套重复,如下所示:
$scope.uploadPic = function(file)
{
alert($scope.taskdetails.id); //task_id e.g 21
alert($rootScope.job_id); //job_id e.g 12
file.upload = Upload.upload(
{
url: 'http://localhost/mobile-data/upload_file.php',
data: {
file: file,
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
} 但在我的upload_file.php上,我无法接收以下值:
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id在console.log,他们工作得很好。但是在服务器端,它没有接收到。这是我的upload_file.php代码
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('content-type: application/json; charset=utf-8');
$_POST = json_decode(file_get_contents('php://input'), true);
$task_id = $_POST["task_id"];
$file = $_FILES["file"];
$job_id = $_POST["job_id"];
var_dump($task_id);
var_dump($job_id);但在var_dump上,它只打印null。帮助我正确地接收这些值。
发布于 2016-01-07 13:58:46
你能确认什么是实际发送到服务器的吗?(在大多数浏览器中,您可以使用F12开发工具来实现这一点。)
data.file的类型是什么?当查看您的php代码时,我假设您正在向服务器发送一个json对象,因此我猜想浏览器无法将file序列化为一个json对象,并最终向服务器发送一个空请求。要解决这个问题,您可以将文件读取为base64数据,以便将其作为字符串发送到json对象中:
var data = {
file: '',
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
};
if($window.FileReader) {
var reader = new FileReader();
reader.onloadend = function() {
data.file = reader.result;
$http.post('http://localhost/mobile-data/upload_file.php', data);
}
reader.readAsDataURL(file);
}然后将该文件作为格式化为data:image/png;base64,...的字符串发送到服务器(您可以在F12工具中看到这一点)。
到达php后,需要对这个base64字符串进行解码才能返回该文件:
$_POST = json_decode(file_get_contents('php://input'), true);
$task_id = $_POST['task_id'];
$job_id = $_POST['job_id'];
if(isset($_POST['file']) && ($_POST['file'] != NULL)
&& preg_match('/data:([^;]*);base64,(.*)/', $_POST['file'], $matches)) {
if($matches && (count($matches) > 2)) {
$datatype = $matches[1];
$file = base64_decode($matches[2]);
}
}注意,当您将数据作为json对象发送到服务器时,$_FILES将无法工作。
编辑:刚刚注意到你在使用ng-档案-上载?然后,数据不是作为json对象发送的,而是作为通常形式的urlencoded数据发送的。在这种情况下,您不应该在php代码中有这一行:
$_POST = json_decode(file_get_contents('php://input'), true);并在javascript中发送数据:
Upload.upload({
url: 'http://localhost/mobile-data/upload_file.php',
method: 'POST',
file: file,
sendFieldsAs: 'form',
fields: {
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
}
})https://stackoverflow.com/questions/34655805
复制相似问题