无法使用AngularJS上传文件及其详细信息

时间:2014-07-10 12:01:13

标签: angularjs

我尝试使用AngularJS上传图像文件及其详细信息。该文件的详细信息将存储在服务器上的JSON文件中。但是,它不起作用。来自服务器的返回信息只是一个空数组。我不知道为什么我的代码不起作用。我要尝试内容类型等等......但仍然没有运气。

我的代码:

<body>

    <div>
        <form ng-controller="Ctrl" ng-submit="save()">
        Title :<input type="text" ng-model="file_details.title"><br>
        Summary: <input type="text" ng-model="file_details.summary"><br>
        File: <input type="file" file-upload><br>
        <button type="submit">save</button>
        </form>
    </div>

<script src="bower_components/jquery/dist/jquery.min.js"></script>  
<script src="bower_components/angular/angular.min.js"></script>
<script>
    //Angular here
    (function(){
        var app = angular.module('myApp', []);

        app.config(function($httpProvider){
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        });

        app.controller('Ctrl', ['$scope', '$http', function($scope, $http){
            $scope.file_details = {};

            $scope.files = [];

            //listening from fileUpload directive
            $scope.$on('fileSelected', function(event, args){
                $scope.$apply(function(){
                    //add the file object to scope's files collection
                    $scope.files.push(args.file);
                });
            });

            $scope.save = function(){
                $http({
                    method: 'POST',
                    url: 'process.php',
                    transformRequest: function (data) {
                        var formData = new FormData();
                        formData.append("file_details", angular.toJson(data.file_details));
                        formData.append("file", data.files);
                    },
                    headers: {
                          'Content-Type': false

                    },
                    data: { 
                        file_details: $scope.file_details,
                        files: $scope.files
                    }
                }).success(function (data, status, headers, config) {
                // alert("success!");
                    console.log(data);
                });
            }

        }]);

        app.directive('fileUpload', function(){
            return{
                link: function(scope, elm, attrs){
                    elm.bind('change', function(event){
                        var files = event.target.files;
                        scope.$emit('fileSelected', { file: files });
                    });
                }
            }
        });


    })();
</script>
</body>

我的服务器代码(仅用于检查数据是否已发送,但仍返回空数组):

print_r($_POST); die();

0 个答案:

没有答案