MVC 将 Base64 字符串转换为图像,但是... System.FormatException

2024-04-02

我的控制器正在以下代码中的请求对象中获取上传的图像:

[HttpPost]
public string Upload()
{
    string fileName = Request.Form["FileName"];
    string description = Request.Form["Description"];
    string image = Request.Form["Image"];

    return fileName;
}

image 的值(至少是它的开头)看起来很像这样:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD/7gAOQWRvYmUAZAAAAAAB/...

我尝试使用以下内容进行转换:

byte[] bImage = Convert.FromBase64String(image);

但是,这给出了 System.FormatException:“输入不是有效的 Base-64 字符串,因为它包含非 Base 64 字符、两个以上的填充字符或填充字符中的非法字符。”

我感觉问题是至少字符串的开头不是 base64,但据我所知,没有一个是。在解码之前我需要解析字符串吗?我错过了一些完全不同的东西吗?


看起来像你may只是能够去掉"data:image/jpeg;base64,"部分从一开始。例如:

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,但我会首先尝试这样做。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC 将 Base64 字符串转换为图像,但是... System.FormatException 的相关文章

随机推荐