简体   繁体   中英

Validate Base64 string

I am converting an image to base64 on a html5 mobile client and posting the string to my webapi service. I try to convert the received string back to an image and I get the following exception

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Pastebin of base64 string is here .

I have read all the suggestions about replaing wrong characters so I wroe this function to and pass my strings into it first yet no luck.

    private string FixBase64ForImage(string Image)
    {
        System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image, Image.Length);

        sbText.Replace("\r\n", String.Empty);

        sbText.Replace(" ", String.Empty);

        sbText.Replace('-', '+');

        sbText.Replace('_', '/');

        sbText.Replace(@"\/", "/");

        return sbText.ToString();
    }

Is there a way to know exactly what character is causing the conversion to fail?

My guess is that you're including the "data:image/png;base64," part at the start of the string - you need to strip that first. You don't need to do anything else - with the text in the pastebin, Convert.FromBase64String handles everything after the "base64," with no problems at all.

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