Reputation: 9065
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?
Upvotes: 2
Views: 2484
Reputation: 4187
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.
Upvotes: 3