Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

how to get base64 string from [object TiBlob] object?

Hi friends,

How can I get base64 string from [object TiBlob] object?

Thanks in advance

— asked February 9th 2011 by yogesh prajapati
  • base64encode
  • tiblob
  • titanium mobile
  • titanium.media.showcamera
0 Comments

10 Answers

  • I'm assuming that the Blob is an image and that you're trying to convert that image into a base64 string. If this is the case, here's how I did it:

    1. Use a canvas element in a HTML5 webview and include an event listener in the HTML page of the webview like so:

      Ti.App.addEventListener('getImageString',function(){
               var imgstr = canvas.toDataURL();
               var base64 = {str:imgstr};
               Ti.App.fireEvent('getBase64',base64);
           });
      

      Notice that you need to use the canvas.toDataURL() method to get the base64 string of whatever is rendered on the canvas object.

    2. Pass the string back to the Titanium app context to do what you need with the string. In the code block above, the fireEvent method is called and in the Ti app context, you should have a Ti.App.addEventListener like so:

    Ti.App.addEventListener('getBase64',function(e){
        var imgStr = e.str;
    });
    

    Now you have the Base64 string in the local variable imgStr that you can use to do whatever you need.

    Hope this helps.

    — answered February 9th 2011 by Brandon Xavier
    permalink
    0 Comments
  • Have you tried the base64encode method? It is documented as taking a string argument, but you could try with a blob.

    — answered February 9th 2011 by Doug Handy
    permalink
    1 Comment
    • Hey Thanks, I already tried it but no luck :(

      — commented February 9th 2011 by yogesh prajapati
  • Hey @Brandon your assumption is right.

    Below is how I achieve image upload to server.

    Titanium code

    var xhr2 = Titanium.Network.createHTTPClient();
    
    xhr2.onload = function(){
                                Ti.API.info('response of image upload');
                                var response = JSON.parse(this.responseText);
                                   //Do the needful
                             };
    
    xhr2.onerror = function(){
        Ti.API.info('in utf-8 error for POST');
    };
    
        // I have used REST webservice
        var web_service_url = Titanium.App.Properties.getString('web_service_url');
        // In para_list I send extra information that I need on server    
        var para_list = 'username='+username+'&password='+password+'&image_type=' + image_type;
        var req_url = web_service_url + '?' + para_list;
    
        Titanium.API.info(req_url);
        xhr2.open("POST",req_url,false);
        // image is [object TiBlob] object
        xhr2.send({media:image});
    

    PHP server code

    //$uploaddir absolute path to uoload directory
    
    $image_name = $uploaddir.basename($_FILES['media']['name']);
    
    $image_size = $_FILES['media']['size'];
    
    if(move_uploaded_file($_FILES['media']['tmp_name'], $image_name))
    {                    
        // Now image is available at $image_name
    }
    

    Hope it helps to someone :)

    — answered February 12th 2011 by yogesh prajapati
    permalink
    0 Comments
  • @Brandon - this looks exactly like what I need, but I dont understand how to actually access the local variable. Put another way, how is it that I pass a Blob into these listeners to get a Base64 string back? Sorry, but a newbie to this. Any assistance most appreciated!

    — answered August 12th 2011 by Carl Vescovi
    permalink
    0 Comments
  • And how do I get the base64 of a wav file in the mobile?

    Thanks

    — answered August 29th 2011 by Leandro Vidal
    permalink
    0 Comments
  • Aaron, thanks a lot! Your module works for me perfectly (WAV files) on a simulator:

    var utils = require('com.clearlyinnovative.utils');
    Ti.API.info("module is => " + utils); 
    
    var f = Ti.Filesystem.getFile(file.path);
    var encoded_audio = utils.base64encode( f.read() );
    

    but it gives an error when I try to put app on iOS Device. Do you know what the problem could be related with?

    [INFO] Performing clean build
    [ERROR] 
    [ERROR] Error: Traceback (most recent call last):
      File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.3/iphone/builder.py", line 1305, in main
        execute_xcode("iphoneos%s" % iphone_version,args,False)
      File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.3/iphone/builder.py", line 1066, in execute_xcode
        output = run.run(args,False,False,o)
      File "/Library/Application Support/Titanium/mobilesdk/osx/1.7.3/iphone/run.py", line 39, in run
        sys.exit(rc)
    SystemExit: 65
    

    Thanks

    — answered January 14th 2012 by Kateryna Lyshchenko
    permalink
    3 Comments
    • I have some images files in my local file system. I am trying to convert image file into base64 data using Titanium Utils. But after the conversion I am getting empty string… here is my sample code

      var f = Titanium.Filesystem.getFile(currIamge);
      var temp = f.read();
      var encodeData = Ti.Utils.base64encode(temp);
      alert("encodeData = "+encodeData);
      

      Here I am getting empty alert. How do I convert a file into base64 data? I am Using Titanium 1.7.5 in iOs platform

      — commented February 16th 2012 by Karthi Ponnusamy
    • Hello,

      I've confirmed that base64 encoding now works as expected on non-strings in 1.8.2 (no need for the great clearlyinnovative.utils workaround anymore.) Here's an example of some code that I use for uploading a base64 encoded .wav to a web service:

      
      

      Hope that helps!

      — commented March 2nd 2012 by Will Dzierson
    • Hmm.. somehow my code never made it. Here it is:

      file = recording.stop();
      Ti.Media.stopMicrophoneMonitor();
      
      //
      // base64 encoding a wav to upload here
      //
      var encoded_audio = Ti.Utils.base64encode(file.toBlob());
      Ti.API.info(encoded_audio);
      
      var data_to_send = {
          "apikey" : "supersecret",
          "action" : "recognize",
          "freeform" : "1",
          "content-type" : "audio/x-wav",
          "output" : "json",
          "audio" : removeNL(String(encoded_audio))
      }; 
      
      var data_string = JSON.stringify(data_to_send);
      xhr = Titanium.Network.createHTTPClient();
      xhr.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
      xhr.open("POST", "yoururl");
      xhr.send(data_string);
      
      xhr.onload = function() {
          Ti.API.info(this.responseText);
      };
      

      — commented March 2nd 2012 by Will Dzierson
  • Hi Will,

    I'm trying this approach, however Ti.Utils.base64encode doesn't seem to return an object for me. (get that error)

    Any suggestions of what to try? I am on Ti 1.8.2 now.

    — answered April 20th 2012 by Prashant Sheth
    permalink
    0 Comments
  • var blob = imageView.toBlob();
    dataUrl = 'data:'+ blob.mimeType + ';base64,' + Ti.Utils.base64encode(blob).text;
    

    Then you can send it through event to webview and set to the img.src

    — answered August 1st 2014 by Andrey Tkachenko
    permalink
    0 Comments
  • I have two questions: 1. Does it work for wav files? I've tried file.read()and it returns a TiBlob object. 2. How do I put the module into a titanium project?

    Thanks

    — answered August 29th 2011 by Leandro Vidal
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.