ghie
ghie

Reputation: 587

How to filter FileUpload Control?

How to add filter to the fileupload control in asp.net? I want a filter for Oasis File (.000).?

Please advice me... thank you very much!

Upvotes: 4

Views: 6389

Answers (3)

BlackKnights
BlackKnights

Reputation: 135

You can use javascript to filter it on server side..

Try this here

Upvotes: 2

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You can use RegularExpressionValidator

<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="fupProduct"
     ErrorMessage="Only .gif, .jpg, .png, .tiff and .jpeg" 
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>

Upvotes: 5

Jon Egerton
Jon Egerton

Reputation: 41579

There's no property on the control. I think the simplest way is to validate the chosen file via javascript. For example

JS Function:

function checkFileExtension(elem) {
        var filePath = elem.value;

        if(filePath.indexOf('.') == -1)
            return false;

        var validExtensions = new Array();
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();

        validExtensions[0] = 'jpg';
        validExtensions[1] = 'jpeg';
        validExtensions[2] = 'bmp';
        validExtensions[3] = 'png';
        validExtensions[4] = 'gif';  
        validExtensions[5] = 'tif';  
        validExtensions[6] = 'tiff';
        validExtensions[7] = 'txt';
        validExtensions[8] = 'doc';
        validExtensions[9] = 'xls';
        validExtensions[10] = 'pdf';

        for(var i = 0; i < validExtensions.length; i++) {
            if(ext == validExtensions[i])
                return true;
        }

        alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
        return false;
    }

Wire it up in page_load:

FileUpload1.Attributes.Add("onchange", "return checkFileExtension(this);")

NOTE: This code was reproduced verbatim from here: http://forums.asp.net/t/1156963.aspx/1?How+to+filter+files+in+file+upload+HTML+control. I didn't write it and I haven't tested it!

Upvotes: 4

Related Questions