简体   繁体   中英

reader.readAsDataURL resulting in a defectuous base64 string?

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://imgur.com/a/aO9PMBz

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

Anyone knows how to fix that?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM