2015-10-21 2 views
0

Этот вопрос не касается отслеживания хода файла во время его загрузки на сервер.Как получить ход выполнения ввода типа = файл?

В моем проекте у меня есть ~ 6GB .csv-файлы, которые мне нужно прочитать и отфильтровать некоторые строки на основе определенных критериев.

С известными событиями легко узнать, когда файл загружен в браузер, но поскольку я обрабатываю довольно большие CSV-файлы, я хотел бы показать пользователю, сколько% файла было загружено в браузер.

Чтобы загрузить CSV, я использую следующую пользовательскую директиву:

angular.module('csv-filter') 
.directive('fileReader', function() { 
    return { 
    scope: { 
     fileReader:"=" 
    }, 
    link: function(scope, element) { 
     $(element).on('change', function(changeEvent) { 
     var files = changeEvent.target.files; 

     console.log('files', files); 
     console.log('waiting for onload event..'); 

     if (files.length) { 
      var r = new FileReader(); 
      r.onload = function(e) { 
       var contents = e.target.result; 
       var filesize = 0; 

       scope.$apply(function() { 
       scope.fileReader = {filename: files[0].name, contents: contents}; 
       }); 
      }; 

      r.readAsText(files[0]); 
     } 
     }); 
    } 
    }; 
}); 

Вот ссылка на мое приложение, где я делаю все это: https://ahref-csv-filter.herokuapp.com/

ответ

0

С HTML5 вы можете загружать файлы с помощью Ajax и jQuery.

HTML-

<form enctype="multipart/form-data"> 
    <input name="file" type="file" /> 
    <input type="button" value="Upload" /> 
</form> 
<progress></progress> 

Теперь Ajax Подавать с нажатием данной кнопки:

$(':button').click(function(){ 
    var formData = new FormData($('form')[0]); 
    $.ajax({ 
     url: 'upload', 
     type: 'POST', 
     xhr: function() { 
      var myXhr = $.ajaxSettings.xhr(); 
      if(myXhr.upload){ 
       myXhr.upload.addEventListener('progress',progressFunction, false); 
      } 
      return myXhr; 
     }, 
     beforeSend: beforeSendHandler, 
     success: completeHandler, 
     error: errorHandler, 
     data: formData, 
     cache: false, 
     contentType: false, 
     processData: false 
    }); 
}); 

Теперь, если вы хотите, чтобы справиться с прогрессом.

function progressFunction(e){ 
    if(e.lengthComputable){ 
     $('progress').attr({value:e.loaded,max:e.total}); 
    } 
} 
0

Вы можете использовать ng-file-upload. Это очень аккуратная директива, позволяющая выполнять многофайловую загрузку и отслеживать ход вашего события загрузки.

ng-file-upload

Официальный Samples

Образец

//inject angular file upload directives and services. 
 
var app = angular.module('fileUpload', ['ngFileUpload']); 
 

 
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) { 
 
    $scope.uploadFiles = function(files, errFiles) { 
 
     $scope.files = files; 
 
     $scope.errFiles = errFiles; 
 
     angular.forEach(files, function(file) { 
 
      file.upload = Upload.upload({ 
 
       url: 'https://angular-file-upload-cors-srv.appspot.com/upload', 
 
       data: {file: file} 
 
      }); 
 

 
      file.upload.then(function (response) { 
 
       $timeout(function() { 
 
        file.result = response.data; 
 
       }); 
 
      }, function (response) { 
 
       if (response.status > 0) 
 
        $scope.errorMsg = response.status + ': ' + response.data; 
 
      }, function (evt) { 
 
       file.progress = Math.min(100, parseInt(100.0 * 
 
             evt.loaded/evt.total)); 
 
      }); 
 
     }); 
 
    } 
 
}]); 
 
**strong text**
.thumb { 
 
    width: 24px; 
 
    height: 24px; 
 
    float: none; 
 
    position: relative; 
 
    top: 7px; 
 
} 
 

 
form .progress { 
 
    line-height: 15px; 
 
} 
 
} 
 

 
.progress { 
 
    display: inline-block; 
 
    width: 100px; 
 
    border: 3px groove #CCC; 
 
} 
 

 
.progress div { 
 
    font-size: smaller; 
 
    background: orange; 
 
    width: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script> 
 
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script> 
 
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script> 
 
<body ng-app="fileUpload" ng-controller="MyCtrl"> 
 
    <h4>Upload on file select</h4> 
 
    <button ngf-select="uploadFiles($files, $invalidFiles)" multiple 
 
      accept="image/*" ngf-max-height="1000" ngf-max-size="1MB"> 
 
     Select Files</button> 
 
    <br><br> 
 
    Files: 
 
    <ul> 
 
    <li ng-repeat="f in files" style="font:smaller">{{f.name}} {{f.$errorParam}} 
 
     <span class="progress" ng-show="f.progress >= 0"> 
 
     <div style="width:{{f.progress}}%" 
 
      ng-bind="f.progress + '%'"></div> 
 
     </span> 
 
    </li> 
 
    <li ng-repeat="f in errFiles" style="font:smaller">{{f.name}} {{f.$error}} {{f.$errorParam}} 
 
    </li> 
 
    </ul> 
 
    {{errorMsg}} 
 
</body>

Смежные вопросы