正则表达式的文件大小

时间:2017-10-22 15:51:33

标签: asp.net regex

我有一个FileUpload控件,想要限制上传文件的大小 什么是文件大小的正则表达式?

我将在Asp.Net中的RegularExpressionValidator中使用它。

更新:

我试图在没有回发的情况下检测文件大小。

1 个答案:

答案 0 :(得分:1)

我在这里看不到你想要用正则表达式做什么......

要限制后端中上传文件的大小,您可以使用ContentLength属性。根据{{​​3}},您可以执行此操作

int fileSize = FileUploadControl.PostedFile.ContentLength;
// Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
if (fileSize > 2100000)
{
    // do something if the file is too big
}

如果您想在客户端进行验证(请注意,它也应该在服务器端完成),您可以执行MSDN example中所述的操作。这是一个应该起作用的示例代码

<input id="FileUpload1" type="file" name="file" />
<span id="errorMessage"></span>

<script type="text/javascript">
    //this code will be executed when a new file is selected
    $('#FileUpload1').bind('change', function() {
        //converts the file size from bytes to Ko
        var fileSize = this.files[0].size / 1024;

        //checks whether the file is .png and less than 1Ko
        if (fileSize > 1) {
          $('#errorMessage').html("The file is too big")
              //successfully validated
        }
    });
</script>