tags:

views:

116

answers:

3

I need to upload an image as part of a create action in an MVC application.

The image will be stored in the Files server and the db will contain a path to that.

I plan to use the follwing tag to get the file:

> <input type="file" id="MyImage" name="MyImageName" />

How do I access and save this in the controller action?

+1  A: 

In your controller action it should come out to

Action(HttpPostedFileBase MyImageName) {
  etc;
}
Min
A: 

You can also get to the file through Request.Files if necessary.

Lobstrosity
+1  A: 

I put this in a BaseController class, from which all my controllers inherit:

    // this just prefixes datetime as yyyyMMddhhmmss to the filename, to
    // be use that no name collision will occur.
    protected static String PrefixFName(String fname)
    {
        if (String.IsNullOrEmpty(fname))
        {
            return null;
        }
        else
        {
            return String.Format("{0}{1}",
                                 DateTime.Now.ToString("yyyyMMddhhmmss"),
                                 fname);
        }
    }

    protected String SaveFile(HttpPostedFileBase file, String path)
    {
        if (file != null && file.ContentLength > 0)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path cannot be null");
            }
            String relpath = String.Format("{0}/{1}", path, PrefixFName(file.FileName));
            try
            {
                file.SaveAs(Server.MapPath(relpath));
                return relpath;
            }
            catch (HttpException e)
            {
                throw new ApplicationException("Cannot save uploaded file", e);
            }
        }
        return null;
    }

Then, in the controller I do:

savedPath = SaveFile(Request.Files["logo"], somepath);
giorgian
Request.Files is empty, but my string field for the file name is being set. My view HTML is: <input id="SitePlan" name="SitePlan" type="file" value="<%= Html.Encode(Model.SitePlan) %>" />
littlechris
Strange... what is the returned value? Also, why are you setting a value attr for the input tag? Notice that you cannot reuse it if you rerun the form (for instance, if the form is invalid and the user has to correct something).
giorgian
Sorted it. Missing name tab, only had id at the view. :)
littlechris