tags:

views:

1353

answers:

6
+1  Q: 

File upload MVC

Hi,

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

+1  A: 

Try this code:

    public ActionResult Upload()
    {
        foreach (string file in Request.Files)
        {
         var hpf = this.Request.Files[file];
         if (hpf.ContentLength == 0)
         {
          continue;
         }

         string savedFileName = Path.Combine(
          AppDomain.CurrentDomain.BaseDirectory, "PutYourUploadDirectoryHere");
          savedFileName = Path.Combine(savedFileName, Path.GetFileName(hpf.FileName));

         hpf.SaveAs(savedFileName);
        }

    ...
    }
Pedro Santos
No Request.Files is empty????
Malcolm
You don't need Request.Files. See this answer: http://stackoverflow.com/questions/765211/file-upload-mvc/765308#765308
bzlm
A: 

Pedro's answer will work. I think FormCollection is only for string POST/GET parameters.

CVertex
+10  A: 

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

AcceptVerbs(HttpVerbs.Post)]
Public ActionResult Upload(HttpPostedFile image)
{
    if ( image != null ) {
        // do something
    }
}

This code is quite in the spirit/design of ASP.NET MVC. The others's code really don't have the spirit, IMHO.

Daniel A. White
To get automatic binding to action method parameters, you have to use HttpPostedFileBase, not HttpPostedFile.
bzlm
A: 

Daniel's example will work only if you change action parameter type from HttpPostedFile to HttpPostedFileBase.

Konard
A: 

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 UploadPlotImadge(HttpPostedFileBase image)
{    
    if ( image != null ) 
    {        
        // do something    
    }

    return View();
}
Brett Rigby
A: 

This answer cites production code examples. Feel free to copy and paste the action code from there.

cottsak