Last post Jul 26, 2007 04:42 PM by xuanvu
Jul 25, 2007 07:22 PM|xuanvu|LINK
I'm trying to integrate ASP.NET FileUpload control to my application right now, and have 2 questions:
1. How do I limit the file types to jpg., .gif., and .png only?
2. How do I limit the file size to 1 MB max?
Thank you very much,
Jul 25, 2007 07:54 PM|Kelsey|LINK
Well to do that all you could do the following:
protected void btnUpload_Click(object sender, EventArgs e)
HttpPostedFile file = (HttpPostedFile)(txtFile.PostedFile);
if ((file != null) && (file.ContentLength > 0))
if (IsImage(file) == false)
// Invalid file type so do something here
int iFileSize = file.ContentLength;
if (iFileSize > 1000000) // 1MB approx (actually less though)
// File is too big so do something here
// all good do what you need to do
private bool IsImage(HttpPostedFile file)
// This checks for image type... you could also do filename extension checks and other things
// but this is just an example to get you on your way
return ((file != null) && System.Text.RegularExpressions.Regex.IsMatch(file.ContentType, "image/\\S+") && (file.ContentLength > 0));
Hope that helps :)
Jul 25, 2007 09:37 PM|xuanvu|LINK
Thank you very much for the code... I got it to limit to the file types, but on the file size, whenever I select a large file and hit Upload, I have this error:
The connection was reset
The connection to the server was reset while the page was loading.
* The site could be temporarily unavailable or too busy. Try again in a few
* If you are unable to load any pages, check your computer's network
* If your computer or network is protected by a firewall or proxy, make sure
that Firefox is permitted to access the Web.
This happens both on my local machine and on the server.
Jul 25, 2007 10:02 PM|Kelsey|LINK
The error you are getting has to do with the maximum request size or something that the server will handle for a request. There is a setting in the web.config file that you can set to adjust it:
Jul 25, 2007 10:03 PM|KyD|LINK
See this post to answer your file size issue...
Jul 25, 2007 10:14 PM|xuanvu|LINK
Thanks again for your help... It's working the way it should now... A question though, is there a way for it to detect the size before doing the upload? Right now, it seems like if I pick a file that's larger than 1 MB, it have to go through the upload routine,
after it's completely done processing the file, if the file is larger than 1 MB then it alerts the user.
Jul 26, 2007 04:17 PM|Kelsey|LINK
I am not aware of a way to know the file size before the upload via regular methods. I am sure if you used an activex control though you could really do whatever you wanted to.
Hope that helps.
Jul 26, 2007 04:42 PM|xuanvu|LINK
Thank you all.