asp.net-mvc Html.BeginForm multipart/form-data 文件上传表单组验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27003305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Html.BeginForm multipart/form-data File Upload form-group validation
提问by You Rule Avi
I have a cshtml file to Upload files to the server.
我有一个 cshtml 文件可以将文件上传到服务器。
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary();
<div class="alert alert-success alert-dismissible" role="alert">@ViewBag.Message</div>
<div class="form-horizontal">
<h4>Upload Data Documents</h4>
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.project_id)
<div class="form-group">
<label class="control-label col-md-2">Some Other File</label>
<div class="col-md-10">
<input type="file" name="someOtherFile" class="form-control" />
<span class="field-validation-error" id="spanfilesomeOtherFile"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Results Comparison</label>
<div class="col-md-10">
<div class="form-group">
<div class="col-md-4">
<input type="file" name="FileUploadResultsComparison" class="form-control" placeholder=".col-md-4"/>
<span class="field-validation-error" id="spanfileResultsComparison"></span>
</div>
<div class="col-md-4">
@if (ViewData["Project"] != null)
{
@Html.DropDownList("resultsComp_project", (SelectList)ViewData["Project"], "Select a Project", new { @class = "form-control", @placeholder = ".col-md-4" })
}
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Memory Usage</label>
<div class="col-md-10">
<div class="form-group">
<div class="col-md-4">
<input type="file" name="FileUploadMemoryUsage" class="form-control" />
<span class="field-validation-error" id="spanfileMemoryUsage"></span>
</div>
<div class="col-md-4">
@if (ViewData["Project"] != null)
{
@Html.DropDownList("memUsage_project", (SelectList)ViewData["Project"], "Select a Project", new { @class = "form-control", @placeholder = ".col-md-4" })
}
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="Submit" id="btnSubmit" value="Upload Files" class="btn btn-default" />
</div>
</div>
}
And my Controller is as follows
我的控制器如下
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
foreach (string upload in Request.Files)
{
if (!(Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)) continue;
HttpPostedFileBase file = Request.Files[upload];
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully";
}
}
}
}
return View();
}
The code above works, including the file validation. However i am having trouble with 2 things regarding the "Project" associated with the file.
上面的代码有效,包括文件验证。但是,我在与文件关联的“项目”方面遇到了两件事。
- How to i send/return the Project(id) associated with each file to the controller?
How do i selectively validate the whether the "Project" DropDown is selected for the file? for example (if i browse and select a file for how do i ensure that a corresponding "resultsComp_project" value is selected in the Dropdown? )
how do i associate file and project if they are selected for both (i.e, name="FileUploadMemoryUsage" & name="FileUploadResultsComparison")
- 如何将与每个文件关联的 Project(id) 发送/返回到控制器?
我如何有选择地验证是否为文件选择了“项目”下拉菜单?例如(如果我浏览并选择一个文件,我如何确保在下拉列表中选择了相应的“resultsComp_project”值?)
如果两者都被选中,我如何关联文件和项目(即,name="FileUploadMemoryUsage" & name="FileUploadResultsComparison")
Please note that the Memory Usage information can be null, code will only process a file & project if they are entered.
请注意,内存使用信息可以为空,如果输入,代码只会处理文件和项目。
采纳答案by You Rule Avi
I just had to modify the controller to handle the validation based on the file being uploaded.
我只需要修改控制器以根据上传的文件处理验证。
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
foreach (string upload in Request.Files)
{
if (!(Request.Files[upload] != null && Request.Files[upload].ContentLength > 0)) continue;
int memUsage_baseline_id = 0;
int timingComp_baseline_id = 0;
if (upload == "FileUploadMemoryUsage" || upload == "FileUploadResultsComparison")
{
if (upload == "FileUploadMemoryUsage")
{
if (Request.Params["memUsage_project"] == null || Request.Params["memUsage_project"] == "")
{
ModelState.AddModelError("Project", "Please Select Project for Memory Usage");
}
else
{
memUsage_baseline_id = int.Parse(Request.Params["memUsage_project"]);
}
}
else
{
if (Request.Params["resultsComp_project"] == null || Request.Params["resultsComp_project"] == "")
{
ModelState.AddModelError("Project", "Please Select Project for Timing Comparison");
}
else
{
timingComp_baseline_id = int.Parse(Request.Params["resultsComp_project"]);
}
}
}
HttpPostedFileBase file = Request.Files[upload];
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully";
}
}
}
}
return View();
}

