C# 输入不是有效的 Base-64 字符串,因为它包含非 Base-64 字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15114044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The input is not a valid Base-64 string as it contains a non-base 64 character
提问by Rohit Verma
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 the same stream is received at the application, it gets manipulated and is no longer a valid Base64 string. Some junk characters are getting introduced into the stream.
我有一个 REST 服务,它读取文件并将其转换为 Byte 数组然后转换为 Base64 字符串后将其发送到另一个控制台应用程序。这部分有效,但是当应用程序接收到相同的流时,它会被操纵并且不再是有效的 Base64 字符串。一些垃圾字符被引入流中。
The exception received when converting the stream back to Byte is
将流转换回 Byte 时收到的异常是
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
输入不是有效的 Base-64 字符串,因为它包含非 Base-64 字符、两个以上的填充字符或填充字符中的非空白字符
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);
回答by Jim Mischel
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
很可能它正在转换为修改后的 Base64,其中+
和/
字符更改为-
和_
。请参阅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('_', '/');
回答by Joe Enos
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:
由于您将字符串作为 JSON 返回,因此该字符串将在原始响应中包含开始和结束引号。所以你的回复应该是这样的:
"abc123XYZ=="
or whatever...You can try confirming this with Fiddler.
或者其他什么......你可以尝试用 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.
我的猜测是result.Content
是原始字符串,包括引号。如果是这种情况,则result.Content
需要先反序列化才能使用它。
回答by Alex Filipovici
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:
作为替代方案,您可以考虑使用 XML 作为响应格式:
[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);
回答by bendecko
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...
回答by Hasan Tuna Oru?
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);
回答by Mahdi Alkhatib
Just in case you don't know the type of uploaded image, and you just you need to remove its base64
header:
以防万一你不知道上传的图片的类型,你只需要删除它的base64
标题:
var imageParts = model.ImageAsString.Split(',').ToList<string>();
//Exclude the header from base64 by taking second element in List.
byte[] Image = Convert.FromBase64String(imageParts[1]);
回答by testing
As Alex Filipovicimentioned 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.
正如Alex Filipovici提到的,问题是编码错误。我读入的文件是UTF-8-BOM
并在Convert.FromBase64String()
. 更改为UTF-8
没有问题的工作。
回答by user193679
And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file
有时它以双引号开头,大多数时候当您从 dotNetCore 2 调用 API 以获取文件时
string string64 = string64.Replace(@"""", string.Empty);
byte[] bytes = Convert.ToBase64String(string64);
回答by mostafa kazemi
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);