2009-09-04 76 views
1

我需要上传一个图像作为MVC应用程序中创建动作的一部分。使用ASP.NET MVC上传图像

图像将被存储在文件服务器中,并且数据库将包含一个路径。

我打算使用follwing标签来获取文件:

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

如何访问和保存该控制器的动作?

回答

1

我把这个在BaseController类,从我所有的控制器继承:

// 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; 
    } 

然后,在控制我做的:

savedPath = SaveFile(Request.Files["logo"], somepath); 
+0

Request.Files是空的,但我的串场为文件名正在设置。我的观点HTML是: ”/> – littlechris 2009-09-04 21:02:09

+1

奇怪...什么是返回的值?另外,为什么你要为输入标签设置一个值attr?请注意,如果您重新运行表单,则无法重用它(例如,如果表单无效且用户必须纠正某些内容)。 – giorgian 2009-09-05 09:09:38

+0

对其进行排序。缺少名称标签,只有在视图中的id。 :) – littlechris 2009-09-05 12:21:39

2

在你的控制器动作应该出来

Action(HttpPostedFileBase MyImageName) { 
    etc; 
} 
0

您也可以通过Request.Files如果有必要获得该文件。