user338195
user338195

Reputation:

How to specify file extension in ASP.Net upload control?

Is there a way to specify a file extension for ASP.NET upload control? E.g. I want to upload images with jpg and png extensions only.

I can implement this easily for a windows application, but struggling with ASP.Net

Thank you

Upvotes: 2

Views: 9655

Answers (4)

richman64
richman64

Reputation: 93

Simplified using LINQ / Lambda:

string ext = Path.GetExtension(fileUpload1.FileName);
string[] validFileTypes = { "bmp", "jpg", "jpeg", "png" };
bool isValidType = validFileTypes.Any(t => ext == "." + t);
if(isValidType)
     'do something

Upvotes: 1

Hemant Kumar
Hemant Kumar

Reputation: 4611

string[] validFileTypes = { "bmp", "jpg", "png" };
    string ext = Path.GetExtension(fileUpload1.FileName);
    bool isValidType = false;

    for (int i = 0; i < validFileTypes.Length; i++)
    {
        if (ext == "." + validFileTypes[i])
        {
            isValidType = true;
            break;
        }
    }

    if (!isValidType)
    {
        lblMessage.Text = "Invalid File Type";
    }
    else
    {
        lblMessage.Text = "File Uploaded Successfullty";
    }

Upvotes: 4

Remy
Remy

Reputation: 12713

If you use Flash, then you could define the file type (obviously this does not help if someone changes the file ending).

We are using NeatUpload and that has worked well for years:
http://neatupload.codeplex.com/

There is a setting for the filetype.

Upvotes: 0

davidsleeps
davidsleeps

Reputation: 9513

You can use Javascript to check whether the filename ends with a particular extension, but this doesn't prevent someone renaming any type of file to be .jpg or .png...so you would want to confirm the actual type of file on the server...

The client-side png and jpg check will help in most cases to prevent a wasted upload though...

Upvotes: 1

Related Questions