我在Asp.Net开发网站,其中一个网页要求用户上传文件。客户端希望将文件大小限制设置为最大5MB。我使用以下代码在web.config
中设置了限制;
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="5242880" /> <!--5MB-->
</requestFiltering>
</security> </system.webServer>
检查文件扩展名并向用户显示错误消息的页面的C#代码具有以下代码。
string[] validFileTypes = { "doc", "docx", "xls", "pdf" };
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
break;
}
}
if (!isValidFile)
{
DisplayMessage.Visible = true;
DisplayMessage.Text = "Invalid file or file size has exceeded it max limit of 5MB. Please upload a file with one of the following extension; <br /><br />" +
string.Join(", ", validFileTypes) + "or a smaller file";
}
else
{
string targetFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
string targetPath = Path.Combine(targetFolder, FileUpload1.FileName);
FileUpload1.SaveAs(targetPath);
DisplayMessage.Visible = true;
DisplayMessage.Text = "File uploaded successfully.";
}
我遇到的问题是,当我尝试上传大于5MB的文件而不是显示错误消息的页面时,它会向我发送stack trace
有人可以告诉我哪里出错了。非常感谢提前!
答案 0 :(得分:1)
在web.config文件中写这个
<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="5242880"/>
</system.web>
//使用label
(id = Label1)控件来显示错误。
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentLength < 5242880)
{
/* your code */
}
else
{
Label1.Text = "File size exceeds maximum limit 5 MB.";
}
}
答案 1 :(得分:0)
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
此外,如果您愿意,可以进行验证client side。
答案 2 :(得分:0)
fileId =文件标记的ID fileMsg = Div的Id,它位于文件输入下面,如
<html>
<input type="file" id="fileId" name="file" onchange="uploadFile()">
<div id="fileMsg"></div>
<script>
function uploadFile() {
var filename = $('#fileId').val().split('.').pop().toLowerCase();
var fileInput = document.getElementById('fileId');
if (filename == 'doc' || filename == 'xls' || filename == 'docx' || filename == 'pdf') {
var filesize=(fileInput.files[0].size);
if (filesize > 5000000) {
$('#fileMsg').html('Invalid File Size');
} else {
$('#fileMsg').html('');
}
} else {
$('#fileMsg').html('Invalid File Type');
}
}
</script>
</html>