Uploading an image using ASP.NET MVC

﹥>﹥吖頭↗ 提交于 2019-12-03 21:42:55

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

In your controller action it should come out to

Action(HttpPostedFileBase MyImageName) {
  etc;
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!