我正在ASP.NET MVC网络系统中执行文件上传功能。文件上传功能正在运行,因此我要做的下一步是验证文件大小。
请参阅附带的代码 部分形式 GEDocumentInfoForm.ascx :
<input type="file" name = "Files" class = "multi" id = "myFile"/>
主要表格 Create.aspx
<asp:Content ID="Content4" ContentPlaceHolderID="ContentCph" runat="server">
<script type="text/javascript">
$(document).on('click', '#btnCreateDocument', function () {
$('#btnCreateDocument').attr('disabled', 'disabled'); // prevent resubmit
Checksize()
document.body.style.cursor = 'wait';
});
function Checksize() {
alert(document.getElementById("myFile").tagName);
var k = document.getElementById("myFile").files[0].size;
alert("file size in KB " + k / 1024);
}
</script>
<% Using (Html.BeginForm("Create", "GEDocument", FormMethod.Post, New With {.enctype = "multipart/form-data", .id = "form"}))%>
<input type="submit" name="Save" value="<%= Detail.Save %>" id="btnCreateDocument" />
<div id="Div1">
<% Html.RenderPartial("GEDocumentInfoForm", Model) %>
</div>
<% End Using%>
</asp:Content>
文件大小验证(不超过2048B)在localhost中正常工作。所以,之后我发布它并部署在我的开发服务器中。当我运行它时,它可以以某种方式通过我的验证。在检查Web浏览器的调试模式后,它返回0作为文件大小。
var k = document.getElementById("myFile").files[0].size;
我试图搜索解决方案,看看是否有人之前遇到过类似的问题。最后,我必须在我的控制器中使用服务器验证。
Dim fileZs As HttpFileCollectionBase = Request.Files
For z As Integer = 0 To (fileZs.Count - 1)
Dim file As HttpPostedFileBase = fileZs(z)
If Not IsNothing(file) AndAlso (file.ContentLength / 1024) > 2048 Then
errors.Concat(New RuleViolation(Message.EmailMustHaveValue, "SelectedToEmails"))
End If
Next
Web.Config (添加了配置,以便它可以在Controller中传递ActionFilterAttribute,因为最长请求时间太长)
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
我认为服务器验证不是用户友好的。我希望如果有人在执行客户端验证以检查文件上传功能中的文件大小时遇到像我这样的问题,专家会给出一些答案。
答案 0 :(得分:0)
这是一个完整的工作示例,注意Request.Files是一个数组,如果您只发送一个文件,则需要选择第一个项目。
要检查的正确属性是ContentLength
还要检查上传后上传文件是否存在于您的文件夹中,因为您需要在要上传的文件夹中拥有写入权限
[HttpPost]
public ActionResult Upload()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
//............
}