smuggledPancakes
smuggledPancakes

Reputation: 10323

Cannot get my base64 string to decode on my javascript client

I am sending data from my java tomcat server to my browser using a WebSocket. I get the error: "Uncaught InvalidCharacterError: 'atob' failed: The string to be decoded is not correctly encoded."

Here is my code:

(java server code):

public void open(Session session)
{
  String base64ImageString = generateImageString();
  try
  {
     session.getBasicRemote().sendText(base64ImageString);
  }
  catch(IOException e)
  {
    e.printStackTrace();
  }
}

private String generateImageString()
{
  int imageData[] = new int[2];
  imageData[0] = 255;
  imageData[1] = 128;
  String base64Image = "";
  for(int i = 0; i < imageData.length; i++)
  {
    try
    {
      base64Image += Base64.encode(Integer.toString(imageData[i]).getBytes("UTF8"));
      catch (UnsupportedEncodingException e)
    } 
    catch( UnsupportedEncodingException e) 
    {
      e.printStackTrace();
    }
  }
  return base64Image;
}

(JavaScript code):

function onMessage(evt)
{
  base64ImageDataString = evt.data;
  imageDataString = window.atob(base64ImageDataString);
}

My base64 string looks like this on the java and javascript side: [B@74193bd0[B@24a6103c

I am using org.glassfish.jersey.internal.util.Base64 if it matters. I am really stumped :(

Upvotes: 0

Views: 2328

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500675

My base64 string looks like this on the java and javascript side: [B@74193bd0[B@24a6103c

That's not base64. That's the concatenation of the result of calling toString() on two byte arrays. You're using a method which returns a byte[], not a string, which means your string concatenation is inappropriate. You could use Base64.encodeAsString - or use a different base64 library entirely (e.g. the iharder one). But really you shouldn't be doing any string concatenation.

Your generateImageString code is completely broken. It's not at all clear why you'd convert an integer to a string, get the UTF-8 representation of that, and then convert the byte array to base64... and then do that in a loop. That's just not the way to get anything meaningful.

I suspect you should actually be starting with a byte[] rather than an int[] - it's not clear what those values are meant to be - but then you want a single call to Base64.encode, passing the byte[] in. If you're calling Integer.toString or concatenating bits of Base64 data, you're doing it wrong.

Upvotes: 2

Justin
Justin

Reputation: 1356

[B@24a6103c represents a byte array as a string since Base64.encode returns a byte array.

You need to convert the byte array to a string before concatenating it to the String base64Image

I think you want to do this:

base64Image += new String(Base64.encode(Integer.toString(imageData[i]).getBytes("UTF8")));

Upvotes: -1

Related Questions