The input is not a valid Base-64 string as it cont

2019-01-13 23:53发布

问题:

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 happens correct but when the same stream is received at the application, it gets manipulated and is no more a valid Base64 string. Some junk characters are getting introduced into the stream.

The exception that i get while converting the stream back to Byte is “The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters”.

At Service:

[WebGet(UriTemplate = "ReadFile/Convert", ResponseFormat = WebMessageFormat.Json)]  
public string ExportToExcel()
  {
      string filetoexport = "D:\\SomeFile.xls";
      byte[] data = File.ReadAllBytes(filetoexport);
      var s = Convert.ToBase64String(data);
      return s;
  }

At Application:

       var client = new RestClient("http://localhost:56877/User/");
       var request = new RestRequest("ReadFile/Convert", RestSharp.Method.GET);
       request.AddHeader("Accept", "application/Json");
       request.AddHeader("Content-Type", "application/Json");
       request.OnBeforeDeserialization = resp => {resp.ContentType =    "application/Json";};
       var result = client.Execute(request);
       byte[] d = Convert.FromBase64String(result.Content); 

回答1:

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('_', '/');


回答2:

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...


回答3:

We can remove unnecessary string input in front of the value.

string convert = hdnImage.Replace("data:image/png;base64,", String.Empty);

byte[] image64 = Convert.FromBase64String(convert);


回答4:

I arranged a similar context as you described and I faced the same error. I managed to get it working by removing the " from the beginning and the end of the content and by replacing \/ with /.

Here is the code snippet:

var result = client.Execute(request);
var response = result.Content
    .Substring(1, result.Content.Length - 2)
    .Replace(@"\/","/");
byte[] d = Convert.FromBase64String(response);

As an alternative, you might consider using XML for the response format:

[WebGet(UriTemplate = "ReadFile/Convert", ResponseFormat = WebMessageFormat.Xml)]  
public string ExportToExcel() { //... }

On the client side:

request.AddHeader("Accept", "application/xml");
request.AddHeader("Content-Type", "application/xml");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/xml"; };

var result = client.Execute(request);
var doc = new System.Xml.XmlDocument();
doc.LoadXml(result.Content);
var xml = doc.InnerText;
byte[] d = Convert.FromBase64String(xml);


回答5:

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.



回答6:

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


回答7:

As Alex Filipovici mentioned the issue was a wrong encoding. The file I read in was UTF-8-BOM and threw the above error on Convert.FromBase64String(). Changing to UTF-8 did work without problems.