I’ve got a View that contains code that allows the user to upload images. I pulled the code from a site that I can’t seem to find. The code works great, but my users have asked to see a preview of the image before submitting the page.
My View has the following for my image and upload button.
<div class="editor-field">
@if (Model.ImageData == null || Model.ImageData.Length == 0) {
@:None
}
else {
<img width="150" height="150" alt="Item Image" src="@Url.Action("GetImage", "ItemManagement")" />
}
<div>Upload new image: <input type="file" name="Image" /></div>
</div>
My BeginForm helper looks like this.
@using(Html.BeginForm("Add", "ItemManagement", FormMethod.Post, new{enctype="multipart/form-data"})) {
So, when my view is posted back, my Add Action in my contoller looks like this.
[HttpPost]
public ActionResult Add(ItemAddModel model, HttpPostedFileBase image) {
if (!ModelState.IsValid) {
return View(model);
}
if (image != null) {
model.ImageMimeType = image.ContentType;
model.ImageData = new byte[image.ContentLength];
image.InputStream.Read(model.ImageData, 0, image.ContentLength);
}
_itemService.AddItem(model);
return RedirectToAction("Index");
}
Like I said everything here works great. But it’s only once the form is submitted and my user opens the page again, can they see the image they’ve uploaded. I’d like to add an Update button, that will get the image and load it into the image control without posting back to the server. I don’t want to store the image in the database until the form is Submitted.
Here is the code in my view. The important parts of this are the submit button’s name being set to ‘UploadImageButton’. This matches a property in my ViewModel which is used by my Action method in my controller. Also, the class=”style-name cancel” keeps my Client side validation from firing.
In my controller I have this code to handle HTTP Posts.
This now allows my users to Upload an image, which does a postback, but doesn’t fire any validation an keeps their other edits in the state they were at the time of the upload.