Base64 encoder truncates returned Sting

417 Views Asked by At

I’m displaying an image file in a HTML img tag using a data src URL that contains the image data in 64 byte in encoded format.

When I get the string from the encoded bytes, its terminated to a handfull of characters from what should be around 100k. I have a roll your own encoding routine that I lifted from somewhere and it works fine, albeit slow.

The file comes from a post of a multipart encoded form. I use Apache Commons' FileItem to parse the posted fields. The file contents are defined as a String there but it contains binary data. If I use my own encoder it works fine on the same data. I also use the same String to upload the file to AWS S3 and it works fine there. I tried bypassing the string thing and if I pass the file's InputStream to Base64.encode() I get the same error. Inspection of the returned encoded string shows its severely truncated.

Below file is a String variable that contains the image. I’ve also tried passing an input stream to encode and get the same results. I’ve tried encode().toString() and encodeToString(). Also tried new String(bytes, “UTF-8”).

I don't understand why Base64.encodeToString is truncating the returned ASCII string. Any help would be appreciated.

Using Java and JSP.

String thumbUrl = "data:image/jpeg;base64," +  Base64.getEncoder().encodeToString(file.getBytes());

<img style="width:200px;" src="<%= thumbUrl %>" />

Update: code and output to demonstrate the problem.

byte[] temp = fileParam.value.getBytes();
System.out.println("input len: " + temp.length);
                
temp = Base64.getEncoder().encode(temp);
System.out.println("enc len: " + temp.length);

String z = new String(temp);
System.out.println("z string len: " + z.length());

System.out.println("enc string len: " + temp.toString().length());
                
String myEncString = NetHelper.encodeBase64(fileParam.value);
System.out.println("my encoder string len: " + myEncString.length());


Output:

input len: 3493
enc len: 4660
z string len: 4660  <<< GOOD string length.  Doesn't render
enc string len: 10  <<< BAD string returned
my encoder string len: 4660
2

There are 2 best solutions below

1
Hryhorii Popov On

Glez,

The problem seems to be not with bytes encoding.

You mentioned that

Below file is a String variable that contains the image.

Have you checked you loaded the file correctly?

Typically, one does not end up with String content when loading binary files in Java.
How do you load it? Have you checked the length of this string?

0
glez On

I found that new String(bytes) returns the correct length string. I get a complete string back but it doesn't render properly so there's something else going on. Perhaps there's a bug in Base64.toString() that truncates the returned string.