0

Since the functions related to DispatcherServlet are implemented by another department of my company, I can only complete the specific business classes of the back-end and the front-end, so I cannot directly return byte[] to the front-end.

So I use

                    Base64.getUrlEncoder().encodeToString(bytes);
                    response.put("data", data);

to return a RESTful json response to my front-end.

But in Java encodeToString, BASE64 util converts the bytes to BASE64 bytes and then returns a String based on ISO_8859_1...

First, How can I convert the string to the ISO_8859_1 byte[]?

Second, How can I decode the byte[] encoded by BASE64?

in frontEnd,

        this.http.pdf(data).subscribe(
          resp => {
            const data = WhatShouldTheMethodBe(respo['data']); //What should the method be?
            let blob = new Blob([data], { type: 'application/pdf' });
            let url = window.URL.createObjectURL(blob);
            let pwa = window.open(url);
            if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
              alert('Please disable your Pop-up blocker and try again.');
            }
          }
        );

Thanks a lot.

ildvzg68472
  • 157
  • 1
  • 9
  • 1
    *"...and then returns a String based on ISO_8859_1..."* You can ignore that part, none of the characters in Base-64 encoding varies from encoding to encoding. Unless you mean the bytes were generated from a string, and the string the bytes came from was ISO-8859-1? – T.J. Crowder Feb 15 '22 at 09:20
  • There has to be an original question we can point this at. Short version: Use [`atob`](https://developer.mozilla.org/en-US/docs/Web/API/atob). – T.J. Crowder Feb 15 '22 at 09:22
  • The [linked question's answers](https://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer) show how to get an `ArrayBuffer` from a Base-64 encoded string. You can then pass that `ArrayBuffer` to the [`Blob` constructor](https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob): `new Blob([buffer], { type: "application/pdf" })`. – T.J. Crowder Feb 15 '22 at 09:26
  • @T.J.Crowder Hi Crowder.. Thanks for your answer.. but if the document of method encodeToString says that "and then constructs a new String by using the encoded byte array and the ISO_8859_1 charset." – ildvzg68472 Feb 15 '22 at 09:26
  • Yes, but again: The characters that Base-64 uses don't vary from one 8-bit encoding to the next (not in any of the common ones). ISO-8859-1, UTF-8, and US ASCII all use the same values for the 64 chars used by Base-64: https://ideone.com/AAAvot So you don't need to worry about that part, just the decoding part, which is handled via `atob`. – T.J. Crowder Feb 15 '22 at 10:02

0 Answers0