1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the solution. In this process to find encoding, will the memory usage increase drastically if I upload a large file of size in GBs ?
@SreeraghAR, thank you for accepting the answer. Yes, I believe so, but it will be released again as soon the task end. I did not know you wanted to upload files in GB -size. There is a method to slice the reading (so you can have for example a progressbar) perhaps it can be used to halt the process and still pass a useful chunk to encoding.js. Will look into it this afternoon, I am quite busy right now.
Thanks for the help
Using slice solved the problem. Memory usage became stable. Thanks
@SreeraghAR, great you got it to work! Nice to hear it really is doable with slice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.