CsharpBeginner
CsharpBeginner

Reputation: 1773

Limit file types to be uploaded

I want to limit the types of files that are uploaded to my site. Im using this function below. Would I write if statements for .jpg || .gif || .jpeg || .png. I don't want people uploading exe's. What is the best way to do this?

if (FileUpload1.HasFile)
    try
    {
        var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
        var Myguid = Guid.NewGuid().ToString("N");

        //Check to make sure its an allowable file to be uploaded???????????        

        var newName = Guid.NewGuid() + FileExtension;
        //Map path to folder
        string realpath = Server.MapPath("Pictures\\") + newName;

        //FileUpload1.SaveAs("C:\\Users\\josh\\Desktop\\JaysVersion\\PicRatingSite\\PicRatingSite\\Pictures" + FileUpload1.FileName);
        FileUpload1.SaveAs(realpath);

        Label1.Text = "File name: " +
             FileUpload1.PostedFile.FileName + "<br>" +

             FileUpload1.PostedFile.ContentLength + " kb<br>" +
             "Content type: " +
             FileUpload1.PostedFile.ContentType;


        InsertMembers insert = new InsertMembers();
        int age = Int32.Parse(txtAge.Text);
        insert.InsertNewMember(txtEmail.Text, Myguid, txtName.Text, txtCity.Text, txtState.Text, txtDescription.Text, age, gender);


        //Get Member Id to Insert into Pictures table
        GetMemberInfo GetID = new GetMemberInfo();
        int UMemberId = GetID.GetMemberId(Myguid);
        Displayme.Text = newName.ToString();

        //Now that i have member Id Lets insert new picture into picture table
        Picture InsertnewPictures = new Picture();
        int insertpics = InsertnewPictures.InserNewPicture(UMemberId, newName, 0);

    }
    catch (Exception ex)
    {
        //Handle the error
        throw ex;
    }
else
{
    Label1.Text = "You have not specified a file.";
}

Upvotes: 0

Views: 682

Answers (2)

Nudier Mena
Nudier Mena

Reputation: 3274

you can filter the type of the file to be upload using a switch statement

var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);

switch(FileExtension.ToLower())
{
    case".jpg":
    case".png":
    case".gif":
    case".jpeg":
        break;
     default:
        Response.Write("this file type is not allowed");
        return;
}

Upvotes: 0

Marc B
Marc B

Reputation: 360862

Do NOT trust the filename the user provides. It's trivial to hack, and someone can easily do "rename nastyvirus.exe cutekittens.jpg" prior to upload. You must user server-side mime type detection to ensure that you really did get an image. Same goes for the MIME type provided by the remote browser. It can also be trivially forged and make "nastyvirus.exe" show up as "text/plain".

Upvotes: 1

Related Questions