我在这个问题上挣扎了几个小时。我是AngularJs的新手。我尝试编写一个小图片,将图像上传到后端服务器。也许,我写错了或犯了一些我自己无法识别的错误。我可以指出导致错误的原因吗?
的index.html
<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Upload image test</title>
</head>
<body layout="column">
<div ng-view></div>
<p>Hello world</p>
<script type="text/javascript" src="https://cdn.bootcss.com/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdn.bootcss.com/angular.js/1.4.4/angular-route.js"></script>
<script type="text/javascript" src="myApp.js"></script>
<script type="text/javascript" src="myController.js"></script>
<script type="text/javascript" src="myService.js"></script>
</body>
</html>
myApp.js
var app = angular.module('myapp', ['ngRoute','$httpProvider']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'myCtrl',
templateUrl: 'uploadImage.html'
})
});
app.run(function($httpProvider)
{
var auth = atob('xxttww:090909');
console.log(auth);
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
myController.js
angular.module('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://127.0.0.1:8000/media/Image/";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]).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]);
});
});
}
};
}]);
myService.js
angular.module('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(){
});
}
}]);
uploadImage.html
html>
<body>
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
</body>
</html>
详细错误: