Search code examples
javascriptjavawebsocketstompsockjs

"The string to be decoded is not correctly encoded " error when trying to decode Base64 in JS which has been encoded in Java


I have a problem when trying to pass some data from Java to JS. The original data is of type byte[].

On the Java side I'm using:

byte[] data = some_data;
return Base64.getEncoder().withoutPadding().encodeToString(data)

On the JS side I'm trying to use:

atob(b64Data)

While I do that I'm experiencing the error from the topic:

DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Note: removing .withoutPadding() yields the same result.

My question is, how to rework the code so that the error no longer appears?


Solution

  • It appears that the problem in question was with STOMP client over WebSocket/SockJS on Spring side rather than the encoded data itself.

    Although the data is sent from the method with signature public String getDataForExcelFile the resulting answer got via the WebSocket looks like this:

    FrameImpl {command, headers, ack, binaryBody, body, (...) } so instead of atob(b64Data) I needed to use atob(b64Data.body).