-2

I have a FileUpload control and want to limit the size of uploaded file.
What is the regular expression for a file size ?

I will use this in RegularExpressionValidator in Asp.Net.

Update :

I'm trying this to detect the file size without postback.

Bengi Besçeli
  • 3,638
  • 12
  • 53
  • 87

1 Answers1

1

I don't see what you want to do with a regex here ...

To limit the size of an uploaded file in the back-end you can use the ContentLength property. As per the MSDN example you can do this

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
}

If you want to do the validation on the client side (note that it should also be done on the server side) you can do what is described in this SO post. Here is an example code that should work

<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>
Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48