Convert base64 image to "input file"

1

Good morning,

I'm making an application in angular that picks up a drawing made in canvas and then upload it as a png image to the server.

This is my function:

$scope.signContract = function(){
    var canvas = document.getElementById("pwCanvasMain");
    var Sign = canvas.toDataURL("image/png");

    ContractsFactory.Sign($scope.contratofirma._EntityId, Sign).success(function (data) {

    }).error(function (error) {
        swal("Algo ha ido mal", error.error, "error");
    });
}

The fact is that in the POST request I am sending an image in base64 and in my server I need to process it as an image under "$ _FILE".

Is there a way to move base64 to an input file?

    
asked by 50l3r 10.03.2017 в 12:27
source

1 answer

3

What you can do is convert that base64 to Blob and then to File .

Example

const URL = 'https://cdn.rawgit.com/guzgarcia/8cd4c934fbb98e87d4c99326f609754e/raw/f1d82051359af79e3f6cfb9f6a11d89272ed532c/grandma-medium-b64.txt';

getBase64Image()
  .then(encoded => {
    let body = encoded.split(',')[1];
    let blob = new Blob([atob(body)], {
      type: 'image/jpg',
      encoding: 'utf-8'
    });
    let file = new File([blob], "Grandma on bycle");
    console.log(file);
  })
  .catch(err => {
    console.debug(err);
  });


function getBase64Image(cb) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', URL);
    xhr.onload = function() {
      if (this.readyState === 4) {
        if (this.status === 200) {
          resolve(this.responseText);
        }
        if (this.status >= 400 && this.status <= 500) {
          reject(this.responseText);
        }
      }
    };
    xhr.send();
  });
}
    
answered by 10.03.2017 / 14:21
source