I have the following action in my ImagesController
:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ImageID,ImageCaption,ImageFile")] Image image)
{
if (ModelState.IsValid)
{
HttpPostedFileBase uploadedImage = Request.Files[0];
if (uploadedImage != null && uploadedImage.ContentLength > 0)
{
// Determining file size.
int FileSize = uploadedImage.ContentLength;
// Creating a byte array corresponding to file size.
byte[] FileByteArray = new byte[FileSize];
// Posted file is being pushed into byte array.
uploadedImage.InputStream.Read(FileByteArray, 0, FileSize);
// Assigning byte array to model property
image.ImageFile = FileByteArray;
}
db.Images.Add(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(image);
}
This is my Image
model:
public class Image
{
public int ImageID { get; set; }
[Display(Name="Caption")]
public string ImageCaption { get; set; }
[Display(Name = "Image")]
public byte[] ImageFile { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
And this is my view that accepts an image/file upload:
@using (Html.BeginForm("Create", "Images", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Image</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ImageCaption, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageCaption, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageCaption, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImageFile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
@Html.ValidationMessageFor(model => model.ImageFile, "", new { @class = "text-danger" })
</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>
}
I am trying to save an image uploaded by a user. However, every time I try to upload a file I get this error
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.
The code in my controller should convert the uploaded file into byte array then assign that array to my ImageFile
model property. The code below ModelState.IsValid
and above db.Images.Add(image)
in my controller doesn't seem to be working.
Questions:
- Is
FileByteArray
assigned to my model property correctly? - Is my form/view correct?
- Why do I keep getting the error?