Monday, June 3, 2013

How to Validate Fileupload Control in Asp.net using Javascript

Introduction: in this I try to explain how we can validate the Fileupload control using Javascript and save path to Database.
Validate Fileupload Control in Asp.net using Javascript

Description:
I have a created table Name DOWNLOAD_ASSIGNMENT. Here ID is primary key.
ID
int
CLASS
varchar(50)
ASSIGNMENT
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>

After that add a new webform to project and put the below given script in Head tag of webform.
<script type="text/javascript">

     function validatefileupload() {

         var arrayExt = ['pdf', 'doc', 'docx', 'txt', 'png', 'PNG', 'jpg','JPG','JPEG','gif','GIF','jpeg', 'ppt', 'zip'];

         var FilesVale = document.getElementById("FileUpload1");

         var Ext = FilesVale.value.substring(FilesVale.value.lastIndexOf('.') + 1).toLowerCase();

         if (arrayExt.indexOf(Ext) <= -1) {

             alert("Upload only pdf,doc,txt,png,jpg,gif,ppt and zip flle");

             return false;

         }

         else {

             alert("File Upload Successfully..")
         }

     }

    </script>

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 Javascript and Save path to Database in Asp.net</b></td></tr>
    <tr><td><table><tr><td>Class Name:</td><td><asp:TextBox ID="txtclass" runat="server"></asp:TextBox></td></tr>
    <tr><td>Assignment:</td><td><asp:FileUpload ID="FileUpload1" runat="server" />
               </td></tr>
    <tr><td>&nbsp;</td><td><asp:Button ID="Button1" runat="server" Text="Save"
            OnClientClick="return validatefileupload();" onclick="Button1_Click"
      /></td></tr></table></td></tr>
    </table>

Now go to .aspx.cs page write below mention code.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
string image = Server.MapPath("~/img/") + Guid.NewGuid() + FileUpload1.PostedFile.FileName;
            FileUpload1.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 DOWNLOAD_ASSIGNMENT (CLASS,ASSIGNMENT) values(@CLASS,@ASSIGNMENT)", con);
            cmd.Parameters.AddWithValue("@CLASS", txtclass.Text);
            cmd.Parameters.AddWithValue("@ASSIGNMENT", 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 Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
Dim image As String = Server.MapPath("~/img/") & Convert.ToString(Guid.NewGuid()) & FileUpload1.PostedFile.FileName
            FileUpload1.PostedFile.SaveAs(image)
            Dim fl As String = image.Substring(image.LastIndexOf("\"))
            Dim split As String() = fl.Split("\")
            Dim newpath As String = split(1)
            Dim imagepath As String = "~/img/" & newpath
            Dim cmd As New SqlCommand("Insert into DOWNLOAD_ASSIGNMENT (CLASS,ASSIGNMENT) values(@CLASS,@ASSIGNMENT)", con)
            cmd.Parameters.AddWithValue("@CLASS", txtclass.Text)
            cmd.Parameters.AddWithValue("@ASSIGNMENT", imagepath)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            cmd.Dispose()
            txtclass.Text = ""
        Catch ex As Exception
        End Try
    End Sub


Now run 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.

No comments:

Post a Comment