Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A custom validation attribute is one way to go:</p> <pre><code>public class ValidateFileAttribute : RequiredAttribute { public override bool IsValid(object value) { var file = value as HttpPostedFileBase; if (file == null) { return false; } if (file.ContentLength &gt; 1 * 1024 * 1024) { return false; } try { using (var img = Image.FromStream(file.InputStream)) { return img.RawFormat.Equals(ImageFormat.Png); } } catch { } return false; } } </code></pre> <p>and then apply on your model:</p> <pre><code>public class MyViewModel { [ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")] public HttpPostedFileBase File { get; set; } } </code></pre> <p>The controller might look like this:</p> <pre><code>public class HomeController : Controller { public ActionResult Index() { var model = new MyViewModel(); return View(model); } [HttpPost] public ActionResult Index(MyViewModel model) { if (!ModelState.IsValid) { return View(model); } // The uploaded image corresponds to our business rules =&gt; process it var fileName = Path.GetFileName(model.File.FileName); var path = Path.Combine(Server.MapPath("~/App_Data"), fileName); model.File.SaveAs(path); return Content("Thanks for uploading", "text/plain"); } } </code></pre> <p>and the view:</p> <pre><code>@model MyViewModel @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.LabelFor(x =&gt; x.File) &lt;input type="file" name="@Html.NameFor(x =&gt; x.File)" id="@Html.IdFor(x =&gt; x.File)" /&gt; @Html.ValidationMessageFor(x =&gt; x.File) &lt;input type="submit" value="upload" /&gt; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload