我尝试在Asp.Net中从FileUpload控件中选择一个文件时启动jQuery方法,但它不起作用。 jQuery方法必须检查所选的文件大小。我该如何解决这个问题?
<script type="text/javascript">
function ValidateUploadButton() {
//this code will be executed when a new file is selected
$('#FileUpload1').bind('change', function () {
//converts the file size from bytes to MB
var fileSize = this.files[0].size / 1024;
//checks whether the file is less than 1 MB
if (fileSize > 1) {
$('#errorMessage').html("The file is too big")
alert("okey");
//successfully validated
}
else {
alert("else");
}
});
}
</script>
<asp:FileUpload ID="FileUpload1" runat="server" ClientValidationFunction="ValidateUploadButton" />
<span id="errorMessage"></span>
答案 0 :(得分:1)
我将ClientValidationFunction属性更改为onchange。
<asp:FileUpload ID="FileUpload1" runat="server" onchange="ValidateUploadButton();" />
<span id="errorMessage"></span>
编辑脚本以删除&#39;更改&#39;现在绑定因为更改而调用了ValidateUploadButton。
<script type="text/javascript">
function ValidateUploadButton()
{
//this code will be executed when a new file is selected
//converts the file size from bytes to Ko
var fileSize = $('#FileUpload1')[0].files[0].size / 1024 / 1024;
// USE THIS BELOW IF THE ONE ABOVE DOESN'T WORK
//var fileSize = $('#<%= FileUpload1.ClientID %>')[0].files[0].size / 1024 / 1024;
//checks whether the file is less than 1 MB
if (fileSize > 1)
{
$('#errorMessage').html("The file is too big")
alert("okey");
//successfully validated
}
else
{
alert("else");
}
}
</script>
修改强>
抱歉,我未能彻底测试。它现在应该工作。正确引用filesize的javascript语法是错误的。另外我添加了1024的额外除法,因此您将以MB而不是KB来获取它。
注意 - 这仅适用于一个文件,不支持多个文件。