我正在一次传递图像和表单数据,但是反之亦然,这里是控制器代码:
var app = angular.module("DemoModule", []);
app.directive("fileInput", function ($parse) {
return {
link: function ($scope, element, attrs) {
element.on("change", function (event) {
var files = event.target.files;
$parse(attrs.fileInput).assign($scope,
element[0].files);
$scope.$apply();
});
}
};
});
app.controller("DemoController", function($scope, $http) {
$scope.CustFormData = {};
$scope.Upload = function () {
var form_data = new FormData();
angular.forEach($scope.files, function (file) {
form_data.append('file', file);
});
$http.post("api/Upload.php",
form_data,
{
CustFormData : $scope.CustFormData,
transformRequest: angular.identity(),
headers:
{'Content-Type': undefined, 'Process-
Data':false}
}).then(function successCallback(response) {
alert(response.data);
});
};
};
这是HTML代码,用于将文本字段上传并发送到 PHP脚本:
<div ng-app="DemoModule" ng-controller="DemoController">
<input type="text" name="firstname" ng-model="CustFormData.firstname">
<input type="text" name="lastname" ng-model="CustFormData.lastname">
<input type="file" file-input="files" ng-model="CustFormData.files">
<button type="submit" ng-click="Upload()">Save</button>
</div>
用于将数据存储到数据库中的PHP脚本:
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata) && !empty($_FILES)){
$request = json_decode($postdata);
$firstname = $request->firstname;
$lastname = $request->lastname;
$path = 'upload/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name']);
}
我的问题是上述代码可以正常工作,但不能同时进行。如果删除formdata,它将存储图像;如果删除图像数据,将存储formdata。谁能告诉我哪里做错了吗?