【发布时间】:2016-05-14 05:59:29
【问题描述】:
我正在我的 ASP.NET MVC Web 系统中执行文件上传功能。文件上传功能正常,所以我下一步要做的是验证文件大小。
请查看附件代码 部分形式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 中运行良好。因此,之后我将其发布并部署在我的开发服务器中。当我运行它时,它可以通过我的验证。进入浏览器调试模式后,文件大小返回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(添加了配置,因为Maximum request太长,可以在Controller中传递ActionFilterAttribute)
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
我认为服务器验证对用户不友好。如果有人在进行客户端验证以检查文件上传功能中的文件大小时遇到像我这样的问题,我希望专家能提供一些答案。
- 为什么发布到开发服务器后总是返回0?
- 是否与服务器安全有关?据我所知,我们将 FileName 设为 C:\fakePath\myFileName。会不会是什么关系?
【问题讨论】:
-
检查您的上传文件夹在服务器上的权限
-
@amirpaia 我已经确认 IIS_IUSERS 可以完全控制 inetpub 中的“APP_Data”文件夹。
-
只是为了更新我仍然无法找出javascript中filesize = 0的根本原因。
function Checksize() { alert(document.getElementById("myFile").tagName); var k = document.getElementById("myFile").files[0].size; alert("file size in KB " + k / 1024); },我决定将验证更改为“服务器端验证”` Dim file As HttpPostedFileBase = fileZs(z) If Not IsNothing(file) AndAlso (file.ContentLength / 1024) > 2048 Then \\ display error message End If `
标签: asp.net asp.net-mvc vb.net filesize