2011-03-22 125 views
1

我有一个简单的情况,我有一个页面上传文件,一些导入。目前,我所拥有的只是在我的页面上输入文件。MVC文件上传验证

这是我的GET控制器看起来像

public ActionResult FileUpload() 
{ 
    return View(); 
} 

这是我的观点看起来像

@{ 
    ViewBag.Title = "FileUpload"; 
} 
<h2>FileUpload</h2> 
<form action="/Home/FileUpload" method="post" enctype="multipart/form-data"> 
<input type="file" id="newFile" name="newFile" /> 
<input type="submit" id="submitButton" value="Submit" /> 
</form> 

,这就是我的职务行为看起来像

[HttpPost] 
    public ActionResult FileUpload(HttpPostedFileBase newFile) 
    { 
     if (newFile.ContentLength > 0) 
     { 
      //do stuff here 
     } 
     return View("Index"); 
    } 

你当然会注意到这里没有提到模型,因为我找不到为这种情况创建模型的方法灰。我想要进行一些非常基本的验证,比如'请在上传之前选择一个文件',这就是所有。

有没有办法实现这个?

在此先感谢

回答

3

创建一个字符串属性NEWFILE模型类,并把所需要的就可以了。

在控制器中接受不是HttpPostedFile,而是您的模型类。

1

您应该手动添加客户端验证:

<input type="file" data-val="true" data-val-required="please select a file" name="file" /> 
@Html.ValidationMessage("file")