Angular.js http post请求文件上传

时间:2015-06-21 00:23:37

标签: javascript angularjs http post

我正在尝试使用Angularjs中的http post将文件发送到服务器。我查了资源,找到了这个:

https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

http://jsfiddle.net/JeJenny/ZG9re/

var myApp = angular.module('myApp', []);

myApp.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]);
                });
            });
        }
    };
}]);

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' + JSON.stringify(file));
        var uploadUrl = "/fileUpload";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };

}]);

但是,如果您尝试将任何类型的文件上传到任何服务器,它似乎无效。

该代码有什么问题吗?

0 个答案:

没有答案