0

I need to convert a photo into an array of bytes. I'm loading this photo with html like this:

<input class="form-control"
           type="file"
           name="filename"
           tooltip="Buscar foto"
           ng-file-select="onFileSelect($files)">

onFileSelect function saves the file in a variable of my scope. This is the code.

$scope.onFileSelect = function ($files) {
        $scope.selectedFile = $files;
    };

Now, I need to convert this file into an array of bytes, to display it as a picture later using data-ng-src =" data: image / png; base64, {{selectedFile}} " but i don't know how to do this. Any idea? Thanks

EDIT This is a picture of $files log.

enter image description here

1 Answer 1

1

check out http://www.javascripture.com/FileReader

So, in your case you could do:

  $scope.onFileSelect = function($file){
  var reader = new FileReader();
  reader.onload = function(e){
    console.log("about to encode");
    $scope.encoded_file = btoa(e.target.result.toString());  
  };
  reader.readAsBinaryString($file);
};

Note there are several ways to read in files with the FileReader object. Great for reading as binary, text, and array buffers!

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

4 Comments

i'm getting this error: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.. I think that maybe is because the parameter is a File
Oh, I see. It looks like you're using a list of files. Would you mind posting the log of what $files is?
Yep, you're definitely in a list. We'll want to drill down to the actual file object. Try $file[0] and let me know if that works.
You're right. Using the first element of the list is working. Thanks!!

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.