AngularJs: How to check for changes in file input fields?

前端 未结 15 1516
傲寒
傲寒 2020-11-22 09:06

I am new to angular. I am trying to read the uploaded file path from HTML \'file\' field whenever a \'change\' happens on this field. If i use \'onChange\' it works but when

15条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:36

    The clean way is to write your own directive to bind to "change" event. Just to let you know IE9 does not support FormData so you cannot really get the file object from the change event.

    You can use ng-file-upload library which already supports IE with FileAPI polyfill and simplify the posting the file to the server. It uses a directive to achieve this.

    
    
    
    

    JS:

    //inject angular file upload directive.
    angular.module('myApp', ['ngFileUpload']);
    
    var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
      $scope.onFileSelect = function($files) {
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $files.length; i++) {
          var $file = $files[i];
          Upload.upload({
            url: 'my/upload/url',
            data: {file: $file}
          }).then(function(data, status, headers, config) {
            // file is uploaded successfully
            console.log(data);
          }); 
        }
      }
    }];
    

提交回复
热议问题