Uploading an image using ASP.NET MVC

2020-06-27 01:35发布

问题:

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:

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);


回答2:

In your controller action it should come out to

Action(HttpPostedFileBase MyImageName) {
  etc;
}


回答3:

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