如何识别来自多个html文件输入的文件?

时间:2012-08-22 21:08:28

标签: asp.net asp.net-mvc-3 forms

我目前有一个包含多个文件输入的表单:

Resume: <input type="file" id="resume" name ="files" /><br />
Cover Letter: <input type="file" id="coverLetter" name ="files" /><br />

在我的后端:

[HttpPost]
public ActionResult Apply(ApplyModel form, List<HttpPostedFileBase> files) 
{
    if (!ModelState.IsValid)
    {
        return View(form);
    }
    else if (files.All( x => x == null))
    {
       ModelState.AddModelError("Files", "Missing Files");
       return View(form);
    }
    else
    {
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
             {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
                file.SaveAs(path);
                <!--- HERE -->
            }
        }
    }
}

我的问题是如何确定该文件是来自id resume还是来自于此处评论的地点的coverLetter。

1 个答案:

答案 0 :(得分:3)

你无法识别它。您需要使用不同的名称:

Resume: <input type="file" id="resume" name="coverLetter" /><br />
Cover Letter: <input type="file" id="coverLetter" name="resume" /><br />

然后:

[HttpPost]
public ActionResult Apply(ApplyModel form, HttpPostedFileBase coverLetter, HttpPostedFileBase resume)
{
    ... now you know how to identify the cover letter and the resume
}

并且为避免大量动作参数使用视图模型:

public class ApplicationViewModel
{
    public ApplyModel Form { get; set; }
    public HttpPostedFileBase CoverLetter { get; set; }
    public HttpPostedFileBase Resume { get; set; }
}

然后:

[HttpPost]
public ActionResult Apply(ApplicationViewModel model)
{
    ... now you know how to identify the cover letter and the resume
}