天天看点

angularjs上传文件到服务器,AngularJS - 上传文件( Upload File)

AngularJS - 上传文件( Upload File)

我们提供了上传文件的示例。 为了开发这个应用程序,我们使用了HTML,CSS和AngularJS。 以下示例显示了如何使用AngularJS上载文件。

upload me

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', ['$https:', function ($https:) {

this.uploadFileToUrl = function(file, uploadUrl) {

var fd = new FormData();

fd.append('file', file);

$https:.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 ' );

console.dir(file);

var uploadUrl = "/fileUpload";

fileUpload.uploadFileToUrl(file, uploadUrl);

};

}]);

结果 (Result)

在Web浏览器中打开上面保存的代码文件。 看到结果。

新页面打开

AngularJS - 登录应用程序( Login Application)