Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, how do i validate the file types that are uploaded ? i only want to allow people to upload their image file types only.

Below is a snippet of code that i use to allow users to upload their file:

private void StartUpLoad()
{
string companyID = this.Label1.Text;

string imgName = FileUpload1.FileName;

string imgPath = "~/Uploads/" + imgName;

int imgSize = FileUpload1.PostedFile.ContentLength;

if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{

if (FileUpload1.PostedFile.ContentLength > 1000000)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
}
else
{

FileUpload1.SaveAs(Server.MapPath(imgPath));
Image1.ImageUrl = imgPath;
Page.ClientScript.RegisterClientScriptBlock(typeof(Page),"Alert","alert('Image saved!')", true);

byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(theImage,0(int)FileUpload1.PostedFile.ContentLength);

int length = theImage.Length;
string fileName = FileUpload1.FileName.ToString();
string type = FileUpload1.PostedFile.ContentType;

int size = FileUpload1.PostedFile.ContentLength;
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{

WP_advBLL canwork = new WP_advBLL();
canwork.ExecuteInsert(theImage, type, size, fileName, length,companyID);
Response.Write("File has been uploaded successfully!");
}
}

}

Any idea how to add on to check for type of files selected?
Posted

As far as i know you cannot limit the file upload control to only certain file types on the client's side. In your server side VB code you already have the file name
string imgName = FileUpload1.FileName
So, you could check if it contains one of the extensions you want to include (.jpg .gif etc) If the file name doesnt include one of those, then alert the user.
 
Share this answer
 
Use the API call FindMimeFromData and compare the returned mime type with a list of allowed types.

For an image file this will return a string of the form, "image/{subtype}" where {subtype} will be something like "jpeg", "tiff" or "bmp" depending upon the image type.

For examples of how to call it see PInvoke : Here

AS you've already got the file content in a byte array you can skip the reading from disk step in the Pinvoke examples.

PS.
In case you are not already aware your maximum size check value should be less than the HTTP MaxRequestLength for the web site/app. If you try and upload a file which is larger than this you'll get an exception. See, Setting up Web.config to allow uploading of large files by ASP .NET applications
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900