The input is not a valid Base-64 string as it contains a non-base64 character

后端 未结 11 1616
难免孤独
难免孤独 2020-11-27 14:37

I have a REST service that reads a file and sends it to another console application after converting it to Byte array and then to Base64 string. This part works, but when th

相关标签:
11条回答
  • 2020-11-27 15:11

    Just in case you don't know the type of uploaded image, and you just you need to remove its base64 header:

     var imageParts = model.ImageAsString.Split(',').ToList<string>();
     //Exclude the header from base64 by taking second element in List.
     byte[] Image = Convert.FromBase64String(imageParts[1]);
    
    0 讨论(0)
  • 2020-11-27 15:15

    Remove the unnecessary string through Regex

    Regex regex=new Regex(@"^[\w/\:.-]+;base64,");
    base64File=regex.Replace(base64File,string.Empty);
    
    0 讨论(0)
  • 2020-11-27 15:15

    Probably the string would be like this data:image/jpeg;base64,/9j/4QN8RXh... First split for / and get the second token.

    var StrAfterSlash = Face.Split('/')[1];
    

    Then Split for ; and get the first token which will be the format. In my case it's jpeg.

    var ImageFormat =StrAfterSlash.Split(';')[0];
    

    Then remove the line data:image/jpeg;base64, for the collected format

    CleanFaceData=Face.Replace($"data:image/{ImageFormat };base64,",string.Empty);
    
    0 讨论(0)
  • 2020-11-27 15:19

    Since you're returning a string as JSON, that string will include the opening and closing quotes in the raw response. So your response should probably look like:

    "abc123XYZ=="
    

    or whatever...You can try confirming this with Fiddler.

    My guess is that the result.Content is the raw string, including the quotes. If that's the case, then result.Content will need to be deserialized before you can use it.

    0 讨论(0)
  • 2020-11-27 15:21

    Very possibly it's getting converted to a modified Base64, where the + and / characters are changed to - and _. See http://en.wikipedia.org/wiki/Base64#Implementations_and_history

    If that's the case, you need to change it back:

    string converted = base64String.Replace('-', '+');
    converted = converted.Replace('_', '/');
    
    0 讨论(0)
  • 2020-11-27 15:22

    Check if your image data contains some header information at the beginning:

    imageCode = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...
    

    This will cause the above error.

    Just remove everything in front of and including the first comma, and you good to go.

    imageCode = "iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...
    
    0 讨论(0)
提交回复
热议问题