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

后端 未结 11 1717
难免孤独
难免孤独 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:22

    And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file

    string string64 = string64.Replace(@"""", string.Empty);
    byte[] bytes = Convert.ToBase64String(string64);
    
    0 讨论(0)
  • 2020-11-27 15:25

    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);
    
    0 讨论(0)
  • 2020-11-27 15:28

    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);
    
    0 讨论(0)
  • 2020-11-27 15:32

    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.

    0 讨论(0)
  • 2020-11-27 15:33
    var spl = item.Split('/')[1];
    var format =spl.Split(';')[0];           
    stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);
    
    0 讨论(0)
提交回复
热议问题