title: Upload File Validation using jQuery Forms in ASP.NET MVC
body: <p>I am working on some ASP.NET MVC code which makes use of the jQuery Forms plug-in to allow users to upload files.</p>
  
  <p>The Form:</p>
  
  <pre><code>&lt;% using (Html.BeginForm("SaveAttachments", "Data", FormMethod.Post, new { enctype = "multipart/form-data", id="SaveAttachments" })) {%&gt;   
          &lt;input type="file" name="consentform" size=30/&gt;
       &lt;input type="file" name="infosheet" size=30/&gt;     
       &lt;input type="file" name="approval" size=30 /&gt;         
  &lt;%} %&gt;
  </code></pre>
  
  <p>The form is submitted using jQuery with the Form plugin:</p>
  
  <pre><code>$('#SaveAttachments").ajaxSubmit({
                      success: function(html, status) {
                          $("#response").append(html);
                      }
  });
  </code></pre>
  
  <p>It is handled by a controller action name SaveAttachments:</p>
  
  <pre><code>public ActionResult SaveAttachments(HttpPostedFileBase consentform, HttpPostedFileBase infosheet, HttpPostedFileBase approval)
          {
              string message = SaveFiles(consentform, infosheet, approval)
              return Content(message);
          }  
  </code></pre>
  
  <p>This works well except in the case of errors which prevent the controller action from being called; Specifically when the file size is too large and a HttpException "Maximum Request Length is Exceeded" is thrown.</p>
  
  <p>What I require is a way of updating the user with a suitable message when such errors occur.</p>
  
  <p>I have considered the following:</p>
  
  <ol>
  <li>Try and use the Forms plugin to
  detect and handle this within the ajaxSubmit() - this
  doesn't appear possible.</li>
  <li>Add some client side validation on
  the files to upload - without using
  Flash or ActiveX, I can't find a way
  of checking file size etc. in IE and FF.</li>
  <li>Handle the HttpException thrown by the Controller.Execute() method, and
  communicate this with the
  SaveAttachments() action - I was
  considering overriding the
  controller.Execute() method to allow
  this.</li>
  </ol>
  
  <p>What is the best method of achieving the necesary validation, and if there is no clean way is handling the exception an acceptable workaround?</p>
  
  <p>Thanks.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I have been reduced to two options:</p>
  
  <ol>
  <li>Use Flash/ActiveX/Silverlight for
  more versatile file upload form.</li>
  <li>Find a way to direct text from the
  content length exceeded exception
  handler to the  displaying the
  status in the form. As the file upload form is
  submitted using an iFrame I'm not
  sure I can do this..</li>
  </ol>