cookieChoices = {};

Friday, 20 September 2013

Validate and upload image files in asp.net

Validate and upload image files in asp.net

Introduction It is always better to validate the file extension before uploading file i.e. you want that user can upload only the files that you want e.g. if you want the user can upload only .jpg, .jpeg, .png, .gif , .bmp files then you have to write the code that can check the extension of the file the user is going to upload. Here is the way:
  • Place a FileUpload control and a button control on design page(.aspx)
<asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUploadImage" runat="server" Text="upload Image"
            onclick="btnUploadImage_Click"  />

C#.Net Code to Validate and upload image files in asp.net
  • In the code behind (.aspx.cs) file write the code:
    private bool IsValidExtension(string filePath)
    {
        bool isValid = false;
        string[] fileExtensions = {".bmp",".jpg",".png",".gif",".jpeg",".BMP",".JPG",".PNG",".GIF",".JPEG"};

        for (int i = 0; i <= fileExtensions.Length - 1; i++)
        {
            if (filePath.Contains(fileExtensions[i]))
            {
                isValid = true;
            }
        }
        return isValid;
    }

    protected void btnUploadImage_Click(object sender, EventArgs e)
    {
        if (IsValidExtension(FileUpload1.PostedFile.FileName))
        {
            //write code to upload file
            string filePath = (Server.MapPath("Uploads/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName);
            FileUpload1.SaveAs(filePath);
        }
        else
        {
            Response.Write("Please upload .jpeg,.png,.gif,.jpg,.bmp image only");
        }
    }

No comments:

Post a Comment