"输入不是有效的Base-64字符串。"使用文件上传时出错

时间:2014-07-21 16:23:24

标签: asp.net-mvc-4 bytearray model-binding httppostedfilebase

我需要在我的视图上上传文件。为了不弄乱HttpPostedFileBase而是为了能够使用字节数组进行模型绑定,我决定扩展ByteArrayModelBinder并实现它,以便它自动将HttpPostFileBase转换为byte []。这是我如何做到的:

public class CustomByteArrayModelBinder : ByteArrayModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var file = controllerContext.HttpContext.Request.Files[bindingContext.ModelName];

            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    var fileBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileBytes, 0, fileBytes.Length);
                    return fileBytes;
                }

                return null;
            }

            return base.BindModel(controllerContext, bindingContext);
        }
    }

    protected void Application_Start()
    {
        ...
        ModelBinders.Binders.Remove(typeof(byte[]));
        ModelBinders.Binders.Add(typeof(byte[]), new CustomByteArrayModelBinder());
    }

完成上述操作之后我应该能够拥有像这样的ViewModel:

    public class Profile
{
    public string Name {get; set;}
    public int Age{get; set;}
    public byte[] photo{get; set;}
}

在视图中,我创建了相应的html元素:

@using (Html.BeginForm(null,null,FormMethod.Post,new { enctype = "multipart/form-data" })){
.........    
@Html.TextBoxFor(x=>x.photo,new{type="file"})
<input type="submit" valaue="Save">
}

但是当我提交表单时,我收到以下错误:

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.

事实上,这不是我的想法,我遵循this link中的指南。不知道该怎么办,因为执行在此行停止:

 return base.BindModel(controllerContext, bindingContext);

任何想法该怎么做?

编辑:控制器操作方法:

 [HttpPost]
 public ActionResult Save(Profile profile){
     if(ModelIsValid){
        context.SaveProfile(profile);
     }
 }

但是甚至没有达到行动方法。问题发生在操作方法之前。

1 个答案:

答案 0 :(得分:1)

有时在转换base64时,+和/字符会更改为 - 和_。所以你必须把它们换成:

string converted = base64String.Replace('-', '+');
converted = converted.Replace('_', '/');

BindModel 类中。