2

I am using this javascript code to read and upload a file to server:

var reader  = new FileReader();
reader.onloadend = function() {
  var bytes = reader.result;
  var ext = file.name.split(".").pop();
  xhr.send("bytes="+bytes+"&type="+ext);
}
reader.readAsDataURL(file);

When I check which parameters are being sent to server (in the developer console), I see this:

https://i.sstatic.net/8Yrdp.jpg

which causes an Illegal base64 character error (I think caused by the spaces in the string).

Anyone knows how to fix that?

4
  • Have you tried using readAsBinaryString rather? Commented Jan 13, 2019 at 12:43
  • with this I got a base64 string too? I need those in the server side. Commented Jan 13, 2019 at 12:46
  • It doesn't, but you could use btoa to convert it afterwards. It's just an idea you could try ^^ Commented Jan 13, 2019 at 12:49
  • I just tried that right now, but the same error happens (java.lang.IllegalArgumentException: Illegal base64 character 20) and the same spaces being shown in the string. Commented Jan 13, 2019 at 12:51

1 Answer 1

3

readAsDataURL doesn't produce a clean base64 string, but rather produces a string in the format:

data:[<mediatype>][;base64],<data>

This format is known as a Data URI. You can obtain the raw base64-data by splitting:

const base64 = reader.result.split (",").pop ()

If your data is still invalid, use readAsBinaryString (which returns a File/Blog) and then use window.btoa to convert it to a base64 string.

Sign up to request clarification or add additional context in comments.

5 Comments

I already doing that in the server side, after the data is sent, and that's what causing the error, because the base64-data have spaces which should not be there.
ok, another person suggested that in the comments, and I just tried this readAsBinaryString already, following his suggestion. But the same error happened.
Have you tried using btoa? Can you post your example image? I haven't experienced a problem like this before, readAsBinaryString should return valid binary data.
How I can run the example? I try download, but do not work on my machine (with chrome or firefox). In the web interface I don't find button to run the example.
It runs in the browser. Just open the console to see the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.