action 代码:

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create( ImageStoreModels imagestoremodels) { if (ModelState.IsValid) { if (Request.Files["ImageData"].ContentLength <= 0) return View(); imagestoremodels.ID = Guid.NewGuid(); HttpPostedFileBase aFile = Request.Files["ImageData"]; int contentLength = aFile.ContentLength; byte[] bytePic = new byte[contentLength]; aFile.InputStream.Read(bytePic, 0, contentLength); imagestoremodels.ImageData = bytePic; imagestoremodels.ImageName = aFile.FileName; //imagestoremodels.ImageCataloge = e_ImageCataloge.; //imagestoremodels.ImageAlt = ""; imagestoremodels.ContentType = aFile.ContentType; db.ImageStoreModels.Add(imagestoremodels); db.SaveChanges(); return RedirectToAction("Index"); } return View(imagestoremodels); }
view 代码

@using (Html.BeginForm("Create", "ImageStore", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>ImageStoreModels</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.ImageCataloge, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListForEnum(model => model.ImageCataloge) @Html.ValidationMessageFor(model => model.ImageCataloge) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @*@Html.TextBoxFor(model => model.ImageData, new { type = "file", style="none"})*@ <input name="ImageData" type="file" /> @Html.ValidationMessageFor(model => model.ImageData) <input name="ImageData" id="ImageData" type="file" /> </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ImageAlt, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ImageAlt) @Html.ValidationMessageFor(model => model.ImageAlt) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> }
提交图片, 上传的时候,总是报: 输入的不是有效的 Base-64 字符串 的错误。
后来,在网上才找到答案:
http://stackoverflow.com/questions/3294023/input-file-autobind-to-byte-aray-in-asp-net-mvc