Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Encode an <input file> to base64 in AngularJs?

I need to save an image into Drupal, through the drupal service/file. For what i understand i need to decode the file into a base64 and send this as a payload for the service/file. How can i get to encode the in order to do this???? I want to do this in javascript.

like image 314
Poncho1984 Avatar asked Jul 09 '13 13:07

Poncho1984


People also ask

Can we convert file to Base64?

Convert Files to Base64Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.

What is Base64 file encoding?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.


3 Answers

I am the author of angular-base64-upload as mentioned by @GrimurD. This directive works perfectly for this scenario. It parses image(or any other file types) into base64-encoding and attach the file info to a model in your scope.

Sample usage:

<input type='file' ng-model='yourModel' base-sixty-four-input>

Once you selected a file, yourModel will have a value of something like:

{
  "filetype": "text/plain",
  "filename": "textfile.txt",
  "base64": "/asdjfo4sa]f57as]fd42sdf354asdf2as35fd4"
}

It also has sample code for decoding the base64 file in your server, using PHP or ruby.

like image 73
Adones Pitogo Avatar answered Sep 25 '22 03:09

Adones Pitogo


I know it's quite old, but I came here for a solution.

In the end I found out that (if you don't want to use external libraries) loading an image in base 64 is as simple as using javascript FileReader.readAsDataURL()

Hopefully my final code will help others beginners like me. It features:

  • Input file with HTML5 input type='file' (inspired by this answer)
  • Trigger input from other html elements (inspired by this answer)
  • Check if browser supports input type='file' (inspired by this answer)

It is also on codepen

angular.module('starter', [])
  .controller('Ctrl', function($scope) {
    $scope.data = {}; //init variable
    $scope.click = function() { //default function, to be override if browser supports input type='file'
      $scope.data.alert = "Your browser doesn't support HTML5 input type='File'"
    }

    var fileSelect = document.createElement('input'); //input it's not displayed in html, I want to trigger it form other elements
    fileSelect.type = 'file';

    if (fileSelect.disabled) { //check if browser support input type='file' and stop execution of controller
      return;
    }

    $scope.click = function() { //activate function to begin input file on click
      fileSelect.click();
    }

    fileSelect.onchange = function() { //set callback to action after choosing file
      var f = fileSelect.files[0],
        r = new FileReader();

      r.onloadend = function(e) { //callback after files finish loading
        $scope.data.b64 = e.target.result;
        $scope.$apply();
        console.log($scope.data.b64.replace(/^data:image\/(png|jpg);base64,/, "")); //replace regex if you want to rip off the base 64 "header"

        //here you can send data over your server as desired
      }

      r.readAsDataURL(f); //once defined all callbacks, begin reading the file

    };


  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>

<body ng-app='starter' ng-controller='Ctrl'>
  <button ng-click='click()'>click to select and get base64</button>
  <br>BASE 64 data:
  <br>
  <span style='color: red'>{{data.alert}}</span>
  <div style='word-wrap:break-word'>
    {{data.b64}}
  </div>
</body>
like image 30
Karlooie Avatar answered Sep 23 '22 03:09

Karlooie


I would recommend you to use https://github.com/ninjatronic/angular-base64.

After following instructions for using this library, you can simply call:

var imageData=$base64.encode(image);

Don't forget to inject in your module:

.module('myApp', ['base64'])
like image 23
Bipin Bhandari Avatar answered Sep 24 '22 03:09

Bipin Bhandari