从控制器到模型中的byte []属性的浅复制字节[]出错

时间:2014-03-07 19:28:57

标签: c# asp.net asp.net-mvc-4

控制器

[AllowAnonymous]
[HttpPost]
public ActionResult Registration(Models.RegistrationModel userReg, HttpPostedFileBase UserPhoto)
{
    if (UserPhoto != null)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            UserPhoto.InputStream.CopyTo(ms);
            userReg.UserPhoto = ms.GetBuffer(); //Remove this line and I get no error.
        }
    }

来自View的模型

public class RegistrationModel
{
    [DataType(DataType.Upload)]
    [Display(Name = "User Photo: ")]
    public byte[] UserPhoto { get; set; }
}

查看包含注册表

@model Models.RegistrationModel

@{  
    ViewBag.Title = "Registration";
    Layout = "~/Views/Shared/_Layout.cshtml";   
}


@using (Html.BeginForm("Registration", "UserAgent", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
   @Html.ValidationSummary(true, "Registration failed.");
   <div>
       <fieldset>
           <legend>Registration</legend>

              <div>@Html.LabelFor(p=>p.UserPhoto)</div>
              <div><input type="file" name="UserPhoto" id="UserPhoto"/></div>

              <input type="submit" value="Register" />
      </fieldset>
   </div>

}

我收到错误

  

System.FormatException输入不是有效的Base-64字符串   包含一个非基础64个字符,两个以上的填充字符,或   填充字符中的非法字符。

Connection: keep-alive Content-Length: 128396 Content-Type: multipart/form-data; boundary=---------------------------1127925655036 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.5 Host: localhost:1274 Referer: http://localhost:1274/UserAgent.mvc/Registration User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0 

2 个答案:

答案 0 :(得分:3)

userReg.UserPhoto = ms.ToArray();

GetBuffer返回内部缓冲区,可以大于它包含的字节

MemoryStream ms = new MemoryStream();
ms.WriteByte(1);
int len = ms.GetBuffer().Length;

len 将为256。

答案 1 :(得分:-1)

using (MemoryStream ms = new MemoryStream())
{
    UserPhoto.InputStream.CopyTo(ms);
    userReg.UserPhoto = ms.GetBuffer(); //Remove this line and I get no error.
}

在持有对其缓冲区的引用后,您将处置MemoryStream。你想做的事:

userReg.UserPhoto = ms.ToArray();