2017-06-19 33 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需要更改 –