jQuery ( Acid) .
:
VIEW:
@if (TempData["imageUploadFailure"] != null)
{
@* Here some jQuery popup for example *@
}
@using (Html.BeginForm("ImageUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Add Image</legend>
<label>Image</label>
<input name="image" type="file" value=""/>
<br/>
<input type="submit" value="Send"/>
}
CONTROLLER:
public ActionResult ImageUpload()
{
return View();
}
[HttpPost]
public ActionResult ImageUpload(HttpPostedFileBase image)
{
var result = ImageUtility.SaveImage("/Content/Images/", 1000000, "jpg,png", image, HttpContext.Server);
if (!result.Success)
{
var builder = new StringBuilder();
result.Errors.ForEach(e => builder.AppendLine(e));
TempData.Add("imageUploadFailure", builder.ToString());
}
return RedirectToAction("ImageUpload");
}
ImageUtility:
public static class ImageUtility
{
public static SaveImageResult SaveImage(string path, int maxSize, string allowedExtensions, HttpPostedFileBase image, HttpServerUtilityBase server)
{
var result = new SaveImageResult { Success = false };
if (image == null || image.ContentLength == 0)
{
result.Errors.Add("There was problem with sending image.");
return result;
}
if (image.ContentLength > maxSize)
result.Errors.Add("Image is too big.");
var extension = Path.GetExtension(image.FileName).Substring(1).ToLower();
if (!allowedExtensions.Contains(extension))
result.Errors.Add(string.Format("'{0}' format is not allowed.", extension));
if (!result.Errors.Any())
{
var newName = Guid.NewGuid().ToString("N") + "." + extension;
var serverPath = server.MapPath("~" + path + newName);
image.SaveAs(serverPath);
result.Success = true;
}
return result;
}
}
public class SaveImageResult
{
public bool Success { get; set; }
public List<string> Errors { get; set; }
public SaveImageResult()
{
Errors = new List<string>();
}
}
, ..