MVC base64转换字符串的形象,但... System.FormatException [英] MVC Convert Base64 String to Image, but ... System.FormatException

查看:470
本文介绍了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.

这篇关于MVC base64转换字符串的形象,但... System.FormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆