我需要在MVC应用程序中上传图像作为创建操作的一部分。
图像将存储在文件服务器中,数据库将包含指向该文件的路径。
我计划使用follwing标签获取文件:
> <input type="file" id="MyImage" name="MyImageName" />
如何在控制器操作中访问和保存它?
答案 0 :(得分:2)
在您的控制器操作中,它应该出现
Action(HttpPostedFileBase MyImageName) {
etc;
}
答案 1 :(得分: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);
答案 2 :(得分:0)
如有必要,您还可以通过Request.Files访问该文件。