2015-04-20 60 views
0

我想上傳圖片或文件的標籤html,但我讀了angularJs不支持這個標籤,所以解決方案是創建一個自定義指令。所以在我的網頁的index.html我寫了這個代碼:與AngularJs上傳文件

<body ng-controller="myController"> 
    <input type="file" file-model="myFile"/> 
</body> 

在我的js文件我寫這篇文章的代碼:

var modulo = angular.module('myApp', []); 


modulo.directive('fileModel', function() { 
    var modulo = angular.module('myApp', []); 
     return { 
       restict: 'A', 
       link: function (scope, element, attr) { 

     } 
} 

我不uderstand我怎麼可以讀取該文件,用戶上傳所以我不明白在鏈接函數中寫什麼。我該如何解決我的問題?有沒有人幫助我?謝謝!

+0

爲什麼你需要使用自定義指令?您可以聽文件輸入的更改事件,並可以正確上傳文件?更多信息 - https://docs.angularjs.org/api/ng/directive/ngChange –

+0

這可能有助於http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs –

+0

我已經使用過https://github.com/danialfarid/ng-file-upload和它的工作正常。 –

回答

0

您可以使用已經建好的模塊。 現在已經有很多Angular.js模塊來執行文件上傳:

https://github.com/nervgh/angular-file-upload/ 
https://github.com/leon/angular-upload 
https://github.com/danialfarid/angular-file-upload 
https://github.com/uploadcare/angular-uploadcare 
0

如果瀏覽器無法讀取該文件不支持的FileReader API。

您的指令應用於文件上傳控件。所以,你可以聽聽它的變化事件。通過此更改事件,可以提取事件中提供的文件對象,發出事件以將其捕獲到控制器。

app.directive('fileUpload', function() { 
return { 
    scope: true, 
    link: function (scope, element, attrs) { 
     /*Every time you select a file or a multiple files, change event is triggered. 
     So, with this on, we are attaching a listener event to it. This event also contains useful data. Like the array of selected files. 

     So, we iterate over the selected files, and emit an event containing file info.*/ 
     element.on('change', function (event) { 
      var files = event.target.files;     
      for (var i = 0;i<files.length;i++) { 

       scope.$emit("fileSelected", { file: files[i] }); 
      }          
     }); 
    } 
}; 

通過此代碼,您正在監聽文件上載控件的更改事件。在變更時,您發出了一個名爲fileSelected的事件,您將在控制器中收到該事件。

function DefaultController($scope){ 
     $scope.files = []; 
     $scope.$on('fileSelected', function($event, args){ 
      $scope.files.push(args.file); 
}; 

請注意,使用此代碼,您只能在範圍內添加文件對象。您仍然需要發送上傳文件的請求。

您可以使用休耕代碼from進行一點修正。

$http({ 
      method: 'POST', 
      url: "/Api/PostStuff", 
      headers: { 'Content-Type': undefined}, 
      transformRequest: function (data) { 
       var formData = new FormData(); 

       formData.append("model", angular.toJson(data.model)); 

       for (var i = 0; i < data.files.length; i++) {       
        formData.append("file" + i, data.files[i]); 
       } 
       return formData; 
      },     
      data: { model: $scope.model, files: $scope.files } 
     }). 
     success(function (data, status, headers, config) { 
      alert("success!"); 
     }). 
     error(function (data, status, headers, config) { 
      alert("failed!"); 
     }); 
+1

很抱歉,您能評論此代碼嗎? 1)element.on('change',function(event)2)var files = event.target.files;謝謝 – Ragnarr

+0

在建議的行上添加了評論。 – Paras

+0

如果我想一個接一個地上傳一個文件,我必須這樣寫嗎? var file = event.target.files;範圍。$ emit(「fileSelected」,file); – Ragnarr