MVC base64转换字符串的形象,但... System.FormatException
我的控制器是获得请求对象的上传的图片在这个code:
My controller is getting an uploaded image in the request object in this code:
[HttpPost]
public string Upload()
{
string fileName = Request.Form["FileName"];
string description = Request.Form["Description"];
string image = Request.Form["Image"];
return fileName;
}
图像的价值(至少它的开始),看起来很像是:
The value of image (at least the beginning of it) looks a lot like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/...
我试着用下面的转换:
I tried to convert using the following:
byte[] bImage = Convert.FromBase64String(image);
然而,给出了System.FormatException:输入是不是有效的Base-64串,因为它含有非基本64字符,两个以上的填充字符,或填充字符之间非法字符
However, that gives the System.FormatException: "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."
我得到的感觉,问题是,至少在字符串的开头不是的base64,但我所知道的都不是。我是否需要对其进行解码之前解析字符串?我失去了完全不同的东西?
I get the feeling that the problem is that at least the start of the string isn't base64, but for all I know none of it is. Do I need to parse the string before decoding it? Am I missing something completely different?
它看起来像你的可能的只是能够剥离出数据:图像/ JPEG; BASE64
部分从一开始。例如:
It looks like you may just be able to strip out the "data:image/jpeg;base64,"
part from the start. For example:
const string ExpectedImagePrefix = "data:image/jpeg;base64,";
...
if (image.StartsWith(ExpectedImagePrefix))
{
string base64 = image.Substring(ExpectedImagePrefix.Length);
byte[] data = Convert.FromBase64String(base64);
// Use the data
}
else
{
// Not in the expected format
}
当然,你可能想使JPEG特定这稍差,但我想尝试,作为一个非常第一遍。
Of course you may want to make this somewhat less JPEG-specific, but I'd try that as a very first pass.