Wednesday, 17 October 2012

Uploading Specific File Types

 

Uploading Specific File Types

 

Here are few methods to specify the file types while uploading using a file upload control.. 

Method 1:


private bool IsValidFile(string fileExtn)

    {

        string[] validFileTypes = { "bmp", "jpg", "png" };

        bool isValidType = false;



        for (int i = 0; i < validFileTypes.Length; i++)

        {

            if (fileExtn == "." + validFileTypes[i])

            {

                isValidType = true;

                break;

            }

        }



        return isValidType;

    }



    protected void b_submit_Click(object sender, EventArgs e)

    {

        HttpPostedFile myPostedFile = fileUpload.PostedFile;



        if (myPostedFile != null && myPostedFile.ContentLength > 0)

        {

            FileInfo finfo = new FileInfo(myPostedFile.FileName);

            string fileExtension = finfo.Extension.ToLower();



            if (IsValidFile(fileExtension))

            {

            //Upload process

            string virtualFolder = "~/uploaddocuments/";

            string physicalFolder = Server.MapPath(virtualFolder);

            fileUpload.SaveAs(physicalFolder + fileUpload.FileName);

            }

            else

            {

                //Invalid File Type
            }

        }         

    }


 
Method 2:



if(FileUploadControl.HasFile)
{
if ((System.IO.Path.GetExtension(FileUploadControl.FileName) == ".xls") || (System.IO.Path.GetExtension.FileUploadControl.FileName) == ".xlsx"))
{
//do your logic
}
}

No comments:

Post a Comment

Thank You for Your Comments. We will get back to you soon.

back to top