**You can check this file size in server side using jquery webmethod**
正如 hoodedperson70所说:
当然,这是一个例子,但我无法测试......它应该可以工作:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#submit1").click(function () {
var file == $("#file1");
if (file.value = "" || file.value == null)
{
alert("You must provide a file.");
}
else
{
ajaxFileUpload();
}
});
});
function ajaxFileUpload()
{
//starting setting some animation when the ajax starts and completes
$("#loading").ajaxStart(function () {
$(this).show();
})
.ajaxComplete(function () {
$(this).hide();
});
/*
preparing ajax file upload
url: the url of script file handling the uploaded files
fileElementId: the file type of input element id
dataType: it supports json, xml
secureuri: use secure protocol
success: call back function when the ajax complete
error: callback function when the ajax failed
*/
$.ajaxFileUpload
(
{
url: 'THE WEB SERVICE URL',
secureuri: false,
fileElementId: 'file1',
dataType: 'json',
success: function (data, status)
{
if (data.success == "true")
{
$("#results").html("Valid file size, " + data.length);
}
else
{
$("#results").html("Invalid file size, " + data.length);
}
},
error: function (data, status, e)
{
alert(data + ", " + e);
}
}
)
return false;
}
</script>
</head>
<body>
<form id="form1" method="POST" action="" enctype="multipart/form-data">
<input type="file" id="file1" name="file1" />
<input type="button" id="submit1" name="submit1" value="Upload (size will be checked)" />
<img src="loading.gif" alt="Loading" id="loading" style="display:none;" />
<br /><br /><br />
<div id="results"></div>
</form>
</body>
</html>
这是网络服务代码:
[WebMethod]
public string CheckFileSize(HttpContext context)
{
var file1 = context.Request.Files[0];
if (file1 != null && file1.ContentLength > 0)
{
if (file1.ContentLength > 1024) // This is the IMPORTANT comparison
{
return "{\"success\":\"true\",\"length\":\"" + file1.ContentLength + "\"}";
}
else
{
return "{\"success\":\"false\",\"length\":\"" + file1.ContentLength + "\"}";
}
}
}
您需要点击此链接:
http ://www.phpletter.com/download_project_version.php?version_id= 34 下载 .js 文件和“loading.gif”文件。在我的示例中,它们位于同一目录中,但您可能没有,因此您需要在必要时更改它们的路径。
我没有意识到他们使用 PHP 作为处理,但这应该仍然可以正常工作。javascript 应该能够将文件提交给任何类型的技术,因此它取决于 Web 服务逻辑。很可能 HttpContext 的使用不适合这种情况,但您可以测试一下。
不仅仅是客户端验证的方式
否则,只需尝试这种方式
if (FileUpload1.PostedFile.ContentLength > 5120) // 5120 KB means 5MB
{
//Display a warning
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
//save the file here
}