0

I am trying to post an image using ASp.NET MVC 3 and Jquery. I have the following code in the view

form action="/profile/upload" method="post" enctype="multipart/form-data">

    <label for="photo">Photo:</label>
    <input name="photo" id="photo" type="file">

    <input value="Upload" type="submit">
</form>

and in the controller

public ActionResult Upload(HttpPostedFileBase photo)
{
    string path = @"D:\Temp\";

    if(photo != null)
        photo.SaveAs(path + photo.FileName);

    return RedirectToAction("Index");
}

What I want is I want to upload only jpg or png files through file upload. and I want to do the validations in JQuery.

Please can anyone suggest a simple method and how I can check the validations before submit is fired..

<form action="/profile/upload" method="post" enctype="multipart/form-data">

    <label for="photo">Photo:</label>
    <input name="photo" id="photo" type="file">

    <input value="Upload" type="submit">
</form>
Sparky
  • 98,165
  • 25
  • 199
  • 285
Marcus25
  • 863
  • 1
  • 15
  • 31

1 Answers1

0

If you are using a modern web browser that supports HTML 5 you could restrict the file types like this:

<input name="photo" id="photo" type="file" accept="image/jpg, image/png" />

As an alternative you could use the jquery.validate plugin to check the file extension of the selected file when the form is submitted and display a validation error accordingly. There will be 2 cases:

  1. You are using the jquery unobtrusive validation that's built-in ASP.NET MVC 3. In this case you will have to write a custom adapter as I have illustrated in this post.
  2. You are directly using the jquery.validate plugin and writing the rules yourself. In this case it is a simple matter of defining the custom rule.
Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • No, thats true. But it should be compatible to old browsers as well. Also, I have to display some error message and bind it some
    , if the validation returns false
    – Marcus25 Mar 03 '13 at 17:20
  • Do you want to use the unobtrusive validation that's built-in or are you using the jquery.validate plugin separately? – Darin Dimitrov Mar 03 '13 at 17:20
  • whichever is easy. I have Jquery.validate plugin. – Marcus25 Mar 03 '13 at 17:23
  • I don't know what you mean by easy. There might be different definitions of it for different people. As I said there are two possible solutions to that and which one to use depends entirely on you. – Darin Dimitrov Mar 03 '13 at 17:24