1

我尝试使用 Angularjs 上传文件,但最终出现错误

<!DOCTYPE html>
<html ng-app = "myApp">
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div ng-controller = "myCtrl">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
</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(){
        })
        .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 = "E:\Backup";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };

}]);


</script>

</body>
</html>

当我运行上面的代码时,出现以下错误

    file is {"webkitRelativePath":"","lastModifiedDate":"2014-04-10T13:01:34.000Z","name":"gvxgfg.txt","type":"text/plain","size":95912} test.html:48
    XMLHttpRequest cannot load file:///E:/Backup. Cross origin requests are only supported for HTTP. angular.js:8165
    Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///E:/Backup'.
        at Error (native)
        at b (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:76:389)
        at t (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:72:120)
        at $get.h (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:70:91)
        at l.promise.then.H (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:97:5)
        at l.promise.then.H (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:97:5)
        at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:98:173
        at h.$get.h.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:40)
        at h.$get.h.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:105:331)
        at h.$get.h.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:370) 

我只是一个初学者。我不知道我哪里出错了。希望有人解决。提前致谢

4

0 回答 0