我正在尝试通过Angularjs上传文件。我正在访问该服务但无法在服务器上获取该文件。我在下面发布了我的代码。请让我知道代码中的错误/修改。
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<form name="demo">
<input type = "file" file-model = "myFile"/>
<button type="submit" ng-click = "uploadFile()">upload me</button>
</form>
</div>
<script>
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(){
console.log('file uploaded');
})
.error(function(){
console.log('file not uploaded');
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "http://172.29.5.86:8080/marketplace/inventory/testImageUpload.service";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
答案 0 :(得分:1)
我建议您使用https://github.com/flowjs/ng-flow。
<强> HTML 强>
<div flow-init
flow-name="flowObject.flow" <!-- optional -->
flow-file-added="fileAdded($file)"> <!-- optional -->
<!-- Your HTML -->
<span class="btn btn-default" data-flow-btn>Select Files</span>
<span class="btn btn-primary" ng-click="uploadFiles()">Upload</span>
</div>
<强>控制器强>
$scope.flowObject = {};
$scope.uploadFiles = function () {
$scope.files = $scope.flowObject.flow.files;
// some logic
myService.uploadFilesSomewhere($scope.files).then(function (response) {
// some other logic
});
};
$scope.fileAdded = function (file) {
// some logic
};