使用Angular $资源上传文件

时间:2016-10-13 20:18:03

标签: angularjs restful-url ng-file-upload

我正在尝试使用angular $ resource上传文件,我能够点击Api,但请求没有任何文件。我也在这里尝试了解决方案:AngularJS: Upload files using $resource (solution)

我的控制器:

                        var formData = new FormData();
                        formData.append('file', $scope.file);
                        appService.manualDataUpload(formData)
                            .then(function (response) {
                              //do something here
                            })
                            .catch(function (error) {
                                logger.error('An error occurred while uploading the file !', error);
                            });

我的工厂服务:

function manualDataUpload(formData) {
            var /** @type {angular.Resource} */
            manualDataUploadResource = $resource(serviceBase + '/ManualDataUpload', formData,
                {
                    save: {
                        method: 'POST',
                        transformRequest: angular.identity,
                        headers: {
                            'Content-Type': undefined
                        }
                    }
                });

            return manualDataUploadResource
                .save()
                .$promise;
        }

1 个答案:

答案 0 :(得分:1)

从$ resource中删除formData并在正文中添加。

function manualDataUpload(formData) {
            var /** @type {angular.Resource} */
            manualDataUploadResource = $resource(serviceBase + '/ManualDataUpload', {},
                {
                    save: {
                        method: 'POST',
                        transformRequest: angular.identity,
                        headers: {
                            'Content-Type': undefined
                        }
                    }
                });

            return manualDataUploadResource
                .save(formData)
                .$promise;
        }