2

I'm trying to convert PNG images, a lot of them to Base64 and then send them over a post request to my server-side application.

I have looked up and I found this function which author has done http://jsfiddle.net/handtrix/yvq5y/ here, that do exactly what I want:

function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
    var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'), dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
    canvas = null; 
};
img.src = url;}

I'm using it this way:

convertImgToBase64URL(model.cells[i].attrs.image["xlink:href"], function(base64Img){
            // Base64DataURL
            console.log(base64Img)
        });

As you can see each cells contains an image, which I need to convert to base64 before sending it over a post request, my question is how can I convert an array of PNG images to Base64 and wait for them to finish and then send my array, I know that this is an ajax request and I can't do this synchronously as it's not very natural to javascript, but I can't seem to find a solution. How this is done properly?

Downgoat
  • 13,771
  • 5
  • 46
  • 69
azelix
  • 1,257
  • 4
  • 26
  • 50
  • You could always enter closure hell... – Downgoat Jun 20 '15 at 10:32
  • You need to make sure that `ctx` and `dataURL` are declared with `var` in that "onload" callback. – Pointy Jun 20 '15 at 10:39
  • You could either use jQuery.Deferred(), or add those base64 strings to an array and send the complete array via ajax. Before sending you may count the `i` iterator and verify if `array_base64[i] !=null` – mk117 Jun 20 '15 at 11:01

2 Answers2

0

The question basically boils down to: How can I wait for a set of asynchronous callback functions

Since this is plain Javascript code, the waiting part is a bit complicated to implement (there are examples in that answer as well), a pretty easy to use option is from the answer suggesting using async.js.

Another possibility is to use a Promise library and wrap the function callback in a promise and then wait for all to be fulfilled (usually all libraries have support for such a utility function)

Community
  • 1
  • 1
vvondra
  • 3,022
  • 1
  • 21
  • 34
0

The best way is to submit the form manually after the conversion of data.

convertImgToBase64URL(model.cells[i].attrs.image["xlink:href"], function(base64Img){
        // Base64DataURL
        console.log(base64Img)
        $('#img2b64').submit()

    });
GuillaumeL
  • 509
  • 3
  • 14
  • from what I understood, the question was asking how to submit the data when *all* are converted – vvondra Jun 20 '15 at 10:40
  • So u must check about deferred and promise. It's allow you to chain ajax call and then use a single callback when all request are done. – GuillaumeL Jun 20 '15 at 11:33