c# – MVC将Base64 String转换为Image,但是…… System.FormatEx
发布时间:2020-12-15 18:14:14 所属栏目:百科 来源:网络整理
导读:我的控制器在此代码中的请求对象中获取上传的图像: [HttpPost]public string Upload(){ string fileName = Request.Form["FileName"]; string description = Request.Form["Description"]; string image = Request.Form["Image"]; return fileName;} image
我的控制器在此代码中的请求对象中获取上传的图像:
[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字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非法字符.” 我觉得问题是至少字符串的开头不是base64,但对于我所知道的一切都不是.在解码之前我需要解析字符串吗?我错过了完全不同的东西吗? 解决方法
看起来你可能只能从头开始删除“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特定,但我会尝试这是第一次通过. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |