How to Validate the Fileupload Control with Validation Control in Asp.net - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

How to Validate the Fileupload Control with Validation Control in Asp.net

Introduction: In this I try to explain how we can Validate the Fileupload Control and save file path to Database in Asp.net with Validation control. Here I use the RegularExpressionValidator Control to validate the Fileupload control to upload only images extension.

Validate the Fileupload Control with Validation Control

Description:
I have a created table Name STUDENT_INFO. Here STUDENT_ID is primary key.
STUDENT_ID
int
STUDENT_NAME
varchar(50)
STUDENT_IMAGE
varchar(MAX)

Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="con" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

Now add a new webform to project. Drag and drop the Fileuplaod, Text box and Button Control from Toolbox as mention below.
<table border="1px solid">
    <tr><td><b>Validate the Fileupload Control using Asp.net Validation Control</b></td></tr>
    <tr><td><table><tr><td>Student Name:</td><td><asp:TextBox ID="txtclass" runat="server"></asp:TextBox></td></tr>
    <tr><td>Upload Image:</td><td><asp:FileUpload ID="fluplaod" runat="server" />
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="fluplaod" ErrorMessage="Upload only .png, .bmp, .jpg, .gif File"            
            ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$"
            Font-Bold="True" ForeColor="#FF3300"></asp:RegularExpressionValidator>
        </td></tr>
    <tr><td>&nbsp;</td><td><asp:Button ID="btnsave" runat="server" Text="Save"
            onclick="btnsave_Click" /></td></tr></table></td></tr>
    </table>

No go to .aspx.cs page and write the below mention code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
protected void btnsave_Click(object sender, EventArgs e)
    {
        try
        {
            string image = Server.MapPath("~/img/") + Guid.NewGuid() + fluplaod.PostedFile.FileName;
            fluplaod.PostedFile.SaveAs(image);
            string fl = image.Substring(image.LastIndexOf("\\"));
            string[] split = fl.Split('\\');
            string newpath = split[1];
            string imagepath = "~/img/" + newpath;
            SqlCommand cmd = new SqlCommand("Insert into STUDENT_INFO (STUDENT_NAME,STUDENT_IMAGE) values(@STUDENT_NAME,@STUDENT_IMAGE)", con);
            cmd.Parameters.AddWithValue("@STUDENT_NAME", txtclass.Text);
            cmd.Parameters.AddWithValue("@STUDENT_IMAGE", imagepath);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            cmd.Dispose();
            txtclass.Text = "";           
        }
        catch (Exception ex)
        {
        }
    }

In VB (.aspx.vb)

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ToString())
    Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsave.Click
        Try
            Dim image As String = Server.MapPath("~/img/") & Convert.ToString(Guid.NewGuid()) & fluplaod.PostedFile.FileName
            fluplaod.PostedFile.SaveAs(image)
            Dim fl As String = image.Substring(image.LastIndexOf("\"))
            Dim split As String() = fl.Split("\"c)
            Dim newpath As String = split(1)
            Dim imagepath As String = "~/img/" & newpath
           Dim cmd As New SqlCommand("Insert into STUDENT_INFO (STUDENT_NAME,STUDENT_IMAGE) values(@STUDENT_NAME,@STUDENT_IMAGE)", con)
            cmd.Parameters.AddWithValue("@STUDENT_NAME", txtclass.Text)
            cmd.Parameters.AddWithValue("@STUDENT_IMAGE", imagepath)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            cmd.Dispose()
            txtclass.Text = ""
        Catch ex As Exception
        End Try
    End Sub


Now run the project and check the result.

Related Articles on Validation:
Ø  How to validate email in asp.net using Javascript

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon