FileReader.readAsDataURL result returning format e

2019-08-11 14:43发布

问题:

I'm using the following to convert an image to a base64 encoded string. On the client website in javascript:

  var reader = new FileReader(); 
  reader.onloadend = function () {
                    data64 = reader.result;
                };

  reader.readAsDataURL(myFile);

Now I pass this data to the server, which does the following:

 var data = Convert.FromBase64String(data64);

However this results in a format exception:

The format of s is invalid. s contains a non-base-64 character, more than two padding characters, or a non-white space-character among the padding characters.

My input file is one of the sample images found on Windows 7 -> My Pictures/Sample Pictures/Tulips.jpeg

How can I attempt to debug what is causing the problem for such a large result output?

回答1:

Okay, I have worked around this by using reader.readAsBinaryString instead and then converting this using btoa.

This seems to be accepted fine in Convert.FromBase64String



回答2:

I experienced the same issue and founds out that my complete dataurl contained not only padding characters at the end, but also padding characters in the middle of the dataurl. I used the following code to fix the base64string (but it still has a bug):

private static string getCleanedBase64String(string base64String)
    {
        string tempString = base64String.Replace("_", "/").Replace("-", "+").Replace("=", "");
        return tempString + new string('=', (4 - tempString.Length % 4) % 4);
    }