Search code examples
javascriptgwtjsni

Convert Base64 String with Gwt


How to convert a base64 String to byte array with Gwt client side code?

This link shows a encode decode, for base64 but not to byte[] array

https://snipt.net/tweakt/gwt-base64/


Solution

  • You have two options:

    1- Use native JS methods btoa and atob, and convert the returned string to a java byte[] array:

     native String btoa(String b64) /*-{
        return btoa(b64);
     }-*/;
     ...
     byte[] result = btoa(myBase64Data).getBytes();
    

    2- Use a pure java implementation of Base64 algorithm. You can just copy the Base64Utils.java included in the gwt-user.jar, and copy it to your client package, and use its methods:

     import my.project.namespace.client.Base64Utils;
     ...
     byte[] result = Base64Utils.fromBase64(myBase64Data);
    

    Normally I use #1 for IE10, FF and webkit browsers, and #2 for old IE.