Search code examples
javascriptangularjsnode.jsmultipartform-datang-file-upload

How to restrict files to UTF-8 encoded only in Angular file upload?


I am using ng-file-upload to upload a text file.

<span type="file" class="btn" ngf-select ng-model="fileUser" name="fileUser" ngf-pattern="'.txt,.TXT'" ngf-accept="'text/plain'"> Select File </span>

Is there any way to accept only UTF-8 encoded text file and reject any othe r type of encoding?


Solution

  • It is not natively supported in ng-file-upload but you can create it yourself. Hook into ngf-change this way:

    ngf-change="checkEncoding($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event)" 
    

    Include encoding.js in your app. When the user select a .txt file, load the content of the file by FileReader and use encoding.js to test the encoding :

    $scope.checkEncoding = function(files, file, newFiles, duplicateFiles, invalidFiles, event) {
      if (!event.target.files) return
      var testFile = event.target.files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        var content = new Uint8Array(e.target.result);
        var encoding = Encoding.detect(content);
        if (encoding != 'UTF8') {
          //alert to the user, reset the file ng-model whatever ...
        }
      }
      reader.readAsArrayBuffer(testFile)
    }
    

    Here is a working plunkr -> http://plnkr.co/edit/1UM9NDpNgRbJ13R67xuf?p=preview