Angularjs 图片上传显示空嵌套对象

Angularjs Image Upload showing empty nested object

我有点困惑如何从基本表单使用 with angular 访问文件数据。我正在关注:(https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs) and youtube (https://www.youtube.com/watch?v=vLHgpOG1cW4)。他们似乎做对了,但当我尝试时,事情似乎以不同的方式进行。无论如何,这是我的 HTML 表格:

<form>
    <div class="form-group">
        <label for="name">Full Name</label>
        <input type="text" ng-model="customer.name" id="name" class="form-control"/>
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" ng-model="customer.email" id="name" class="form-control"/>
    </div>
    <div class="form-group">
        <label for="file">Image</label>
        <input type="file" file-model="customer.file" id="file" class="form-control"/>
    </div>
    <div class="form-group">
        <button type="submit" ng-click="submit()" class="btn btn-primary">Submit</button>
    </div>
</form>

和指令

app.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

最后是控制器:

app.controller('CustomerController', ['$scope','CustomerService', function($scope, CustomerService){
    $scope.customer = {};
    CustomerService.save($scope.customer);
}]);

当我 {{ customer }} 在我看来,我得到这样的东西:

{"name":"Robert DeNiro","email":"robie@godfather.com","file":{}}

正是最后一个空的 "file":{} 文件对象导致我无法将 post 的值发送到服务器。

这是我的客户服务代码:

var CustomerService = function($resource) {

        return $resource('advertisements/:id', { id: '@_id' }, {
            update: {
                method: 'PUT' // this method issues a PUT request
              },
        save: {
            method: 'post',
            transformRequest: angular.identity,
            'Content-Type': undefined
        }
    });
    };

    CustomerService.$inject = ['$resource'];
    app.service('CustomerService', CustomerService);

我在所有字段上使用 Laravel 5.1 并报告验证错误 'required',这表明发送了一个空对象。提前致谢。

可能是表单需要属性 enctype="multipart/form-data".

我在 CustomerController 中添加了一个 submit() 方法,如下所示:

$scope.submit = function(){
    var file = $scope.customer.file;
    console.log('file is ' );
    console.log(file.name);
    console.log($scope.customer.file);
    console.dir($scope.customer.file);
};

在那里你可以看到我已经尝试使用 console.log()console.dir() 进行试验,我似乎得到了结果。例如,如果我 console.log($scope.customer)console.dir($scope.customer) 它会给我包含所有文件详细信息的嵌套文件对象。它看起来像这样:

> Object {name: "robert deniro", email: "robie@godfather.com", file: File}
> Object

注意 file: File 因此我可以像这样在 submit() 中访问文件 contents/object:console.log(file.name)console.log(file.type)console.log(file.size).我不知道为什么我一直想念它。我希望有人从我的错误中吸取教训。