Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload MVC

Tags:

asp.net-mvc

With the following markup in my view:

<form action="Categories/Upload" enctype="multipart/form-data" method="post">
    <input type="file" name="Image">
    <input type="submit" value"Save">
</form>

And in my controller:

public ActionResult Upload(FormCollection form)
{
    var file = form["Image"];
}

The value of file is null. If I try it in a different view using a different controller Controller and it works with the same code.

I have VS2008 on Vista, MVC 1.0.

Why?

Malcolm

like image 611
Malcolm Avatar asked Apr 19 '09 10:04

Malcolm


People also ask

How do I upload files to IFormFile?

Upload Single FileTo add view, right click on action method and click on add view. Then select View from left side filter and select Razor View – Empty. Then click on Add button. Create design for your view as per your requirements.


2 Answers

Use HttpPostedFileBase as a parameter on your action. Also, add the AcceptVerb attribute is set to POST.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(HttpPostedFileBase image)
{
    if ( image != null ) {
        // do something
    }
    return View();
}

This code is quite in the spirit/design of ASP.NET MVC.

like image 119
Daniel A. White Avatar answered Sep 23 '22 15:09

Daniel A. White


Not to be picky here or anything, but here's how the code ought to look, as Daniel is missing a few minor details in the code he's supplied...

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadPlotImage(HttpPostedFileBase image)
{    
    if ( image != null ) 
    {        
        // do something    
    }

    return View();
}
like image 43
Brett Rigby Avatar answered Sep 20 '22 15:09

Brett Rigby