无法在AngularJS/NodeJS中上传文件。

12 浏览
0 Comments

无法在AngularJS/NodeJS中上传文件。

我目前已经创建了一个包含链接和控制器的指令,在将其插入到输入文件时,会发送HTTP post请求到nodeJS中的API。问题出现在指令中:

我想知道:我做得对吗?

在控制台日志中打印的错误信息如下:

TypeError: $http(...).success不是一个函数

[更多信息]

可能未处理的拒绝:{"data":"Multipart: Boundary not found Error: Multipart: Boundary not found\n at new

HTML:


指令:

App.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) { 
                var file = event.target.files[0];
                scope.file = file ? file : undefined;
                scope.$apply(); 
                scope.check();
            });
        },
        controller: function($scope, $http) {
            $scope.check = () => { 
                if($scope.file) {
                    $http({
                        method: 'POST',
                        url: '/card/upload-image',
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        data: {
                            upload: $scope.file
                        },
                        transformRequest: function (data, headersGetter) {
                            var formData = new FormData();
                            angular.forEach(data, function (value, key) {
                                formData.append(key, value);
                            });
                            var headers = headersGetter();
                            delete headers['Content-Type'];
                            return formData;
                        }
                    })
                    .success(function (data) { 
                        console.log(data)
                    })
                    .error(function (data, status) {
                        console.log(data, status)
                    });                 
                }
            }
        } 
    };
});

0