2017-06-19 35 views
0

我想知道如何使用angularjs上传文件,而无需使用外部库和只有一个上传按钮? 我已经寻找了一段时间的解决方案,并找到了一个解决方案是非常接近我想要的,如下:angularjs用单个上传按钮上传文件

<div ng-controller = "myCtrl"> 
    <input type="file" file-model="myFile"/> 
    <button ng-click="uploadFile()">upload me</button> 
</div> 

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 '); 
     console.dir(file); 
     var uploadUrl = "/fileUpload"; 
     fileUpload.uploadFileToUrl(file, uploadUrl); 
    }; 

}]); 

http://jsfiddle.net/JeJenny/ZG9re/

不过,我想只有一个上传按钮,并在上述情况下,我怎样才能触发uploadFile()?

回答

0

更新您的提琴:http://jsfiddle.net/ZG9re/7080/

HTML

<div ng-controller = "myCtrl">  
    <button> 
    <input type="file" class="input" id="myfile" file-model="myFile"><a href="">Upload Me</a> 
    </button>  
</div> 

CSS

#myfile { 
    opacity: 0; 
    position: absolute; 
} 

所以,现在当你点击 “上传我” 你会得到的文件浏览器。

更新

请检查:http://jsfiddle.net/ZG9re/7081/

+0

我是新来angularjs。我想知道下面两行是什么意思?谢谢!的document.getElementById( “测试”)classList.remove( “打开”)。 <! - scope.uploadFile(); - > – diane

+0

我很抱歉这里是更新的代码:http://jsfiddle.net/ZG9re/7081/我补充说,当我测试某些东西时,你不需要运行你的代码,你可以删除那个代码代码 –

+0

因此,您不需要对JavaScript进行任何更改,只需HTML和CSS需要更改 –