天天看點

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)