我想上传一个文件。我将MVC3与剃须刀一起使用。我有以下视图模型:
Public Class ImportL2EViewModel
<Required(AllowEmptyStrings:=False, ErrorMessage:="L2E name required")>
Public Property Name As String
Public Property File As HttpPostedFileBase
End Class
在我看来,我创建了一个表单:
@Using Html.BeginForm("Import", "L2ECreationWizard", FormMethod.Post, New Dictionary(Of String, Object) From {{"enctype", "multipart/form-data"}})
@<div class="welcome-box acenter">
<div style="display: block; text-align: left; width: 330px; margin: auto;">
<div class="property">
@Html.LabelFor(Function(m) m.Name)
@Html.TextBoxFor(Function(m) m.Name)
</div>
<div class="property">
@Html.LabelFor(Function(m) m.File)
@Html.TextBoxFor(Function(m) m.File, New With {.type = "file"})
</div>
</div>
<div class="actionBar">
<a class="import fright button" href="#">Import</a>
</div>
</div>
End Using
生成的 html 如下所示:
<form method="post" enctype="multipart/form-data" action="/L2ECreationWizard/Import" novalidate="novalidate">
<div class="welcome-box acenter">
<div style="display: block; text-align: left; width: 330px; margin: auto;">
<div class="property">
<label for="Name">Name</label>
<input type="text" value="" name="Name" id="Name" data-val-required="L2E name required" data-val="true">
</div>
<div class="property">
<label for="File">File</label>
<input type="file" value="" name="File" id="File">
</div>
</div>
<div class="actionBar">
<a href="#" class="import fright button">Import</a>
</div>
</div>
</form>
我将表单发布到以下操作方法:
<HttpPost()>
Function Import(vm As ImportL2EViewModel) As ActionResult
' Nothing yet
End Function
发布后,我可以看到vm.Name
填写完毕,但vm.File
Nothing
. Request.Files.Count
0
.我做错了什么?我在SO上看到过类似的问题,但没有任何效果。我迷路了...
在HttpPostedFileBase file
方法中添加参数,如下所示:
<HttpPost()>
Function Import(vm As ImportL2EViewModel, file As HttpPostedFileBase) As ActionResult
Dim fileName = Path.GetFileName(file.FileName)
Dim physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName)
// The files are not actually saved in this demo
// file.SaveAs(physicalPath)
...
End Function
并从模型中删除 HttpPostedFileBase 属性。它是 Request 对象的一部分,因此无法添加到模型中。
如果您允许选择多个文件,那么这就是您需要能够循环遍历上传的每个文件
<HttpPost()>
Function Import(vm As ImportL2EViewModel, attachments As IEnumerable(Of HttpPostedFileBase)) As ActionResult
For Each file As var In attachments
Dim fileName = Path.GetFileName(file.FileName)
Dim physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName)
' The files are not actually saved in this demo
' file.SaveAs(physicalPath);
Next
...
End Function