Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pictures validation in MVC

Goal:
Make a evaluation of the picture's format, width and height and then saving it in my program.

problem:
Don't know how to use the HttpPostedFileBase file and then sending it to Image newImage = Image.FromFile(xxxx); without saving the picture in my program.

  1. Validation
  2. save picture in my "App_Data"
[AcceptVerbs(HttpVerbs.Post)]  
public ActionResult Add(HttpPostedFileBase file)  
{
    if (file.ContentLength > 0)
    {
        Image newImage = Image.FromFile(xxxx);      
    }

    return Index();  
 } 
like image 632
What'sUP Avatar asked Feb 03 '11 15:02

What'sUP


People also ask

How is validation done in MVC?

Validation is carried out using the jQuery Validation library. Generally, in webform based applications, we make use of JavaScript in order to do client side validations. In MVC, client side validation do not introduce any JavaScript in the code to carry out validation.

What is image validation?

Image validation occurs in Gateway Server image processing threads. Image Compliance collects the validation data so it can apply the specified set of image validation rules, which allows a rule set to execute the same image test using different threshold criteria.

Where is data validation in MVC?

You validation should be in Model section of MVC. As models have various fields, only models can know what combination of inputs make that model valid.


2 Answers

You could do this somehow like the following snippet. Notice the System.Drawing namespace reference, you will need for the Image.FromStream() method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(HttpPostedFileBase httpPostedFileBase)
{
    using (System.Drawing.Image image = System.Drawing.Image.FromStream(httpPostedFileBase.InputStream, true, true))
    {
        if (image.Width == 100 && image.Height == 100)
        {
            var file = @"D:\test.jpg";
            image.Save(file);
        }
    }

    return View();
}
like image 94
Martin Buberl Avatar answered Sep 28 '22 17:09

Martin Buberl


HttpPostedFile has a stream property that is the uploaded data. Use that as with the Image.FromStream method to load the image.

I'd suggest you read the help about HttpPostedFile here:

http://msdn.microsoft.com/en-us/library/SYSTEM.WEB.HTTPPOSTEDFILE(v=vs.100,d=lightweight).aspx

Simon

like image 45
Simon Halsey Avatar answered Sep 28 '22 16:09

Simon Halsey