FileReader.readAsDataURL result returning format exception when entered in Convert.FromBase64String

三世轮回 提交于 2019-12-24 14:55:05

问题


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);
    }


来源:https://stackoverflow.com/questions/32530941/filereader-readasdataurl-result-returning-format-exception-when-entered-in-conve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!