Home > .net 2.0, .net 3.0, .net 3.5, c#, Microsoft, Visual Studio 2005, Visual Studio 2008 > Verifying Extensions and MIME Types of FileUpload

Verifying Extensions and MIME Types of FileUpload

April 7, 2008

The FileUpload control is REALLY handy to upload files from a client, through the web, into a database table or the web server.  The control wraps up the HttpPostedFile object (into .PostedFile); however, there isn’t a way to “filter” on the fly.  This was a recent discussion in the Microsoft newsgroups today, so I figured I’d work out what it’d take to implement a “better” file upload control.

The control, inheriting the FileUpload class as a base class, implements quite quickly.  I’m sure you could go farther, but this works out nicely.

NOTE: In my experience, filtering by MIME type (aka content type) is much more reliable than parsing out the uploaded file’s file name and trying to grok the extension.  Extensions are far too easily changed.😉

public partial class BetterFileUpload : FileUpload

{

public BetterFileUpload()

       {

              ValidContentTypes = new List<string>();

}

 

public IList<string> ValidContentTypes { get; private set; }

 

public void AddValidContentType(string contentType)

{

              ValidContentTypes.Add(contentType);

}

 

public void AddValidContentType(string[] contentTypes)

{

              foreach (var contentType in contentTypes)

{

ValidContentTypes.Add(contentType);

}

}

 

public bool HasValidContentType()

{

return

ValidContentTypes.Contains(PostedFile.ContentType);

}

}

This partial class simply adds a few methods and a single property to the FileUpload class—ValidContentTypes.

HasValidContentType looks through the ValidContentTypes and tries to match it to the PostedFile’s content type—then returns a boolean.

Using this code is simple.

To setup a few valid content types, you can either pass them one-by-one or as an array (you could also pass in a collection of some sort and use the ToArray() method to convert it back into an array).  You could also store these in the web.config file or another reusable source to keep the code clean.

protected void Page_Load(object sender, EventArgs e)

{

betterFileUpload.AddValidContentType(“text/plain”);

 

betterFileUpload.AddValidContentType(

              new[] {“application/msword”, “application/pdf”});

}

After the valid content types have been added and we’re ready to fetch the stream from the FileUpload object, we now have a tidy boolean method to check.

protected void ReadFileButton_Click(object sender, EventArgs e)

{

if (betterFileUpload.HasValidContentType())

       {

              InfoLabel.Text = “Valid ContentType: “ +

                     betterFileUpload.PostedFile.ContentType;

}

else

       {

              InfoLabel.Text = “Invalid ContentType: “ +

                     betterFileUpload.PostedFile.ContentType;

}

}

Works well and is reusable!

%d bloggers like this: