How to upload images using ajax AsynFileUpload Control and Create a Photo gallery of your friends like Google+ and Facebook in asp.net

By
The AsynFileUpload Ajax control enables you to upload the files asynchronously on server.The uploading of files can be confirmed at both the server and client side. You can save the uploaded images by using SaveAs() method.This control works the uploads the files without doing any post pack.  This control shows the Loading image while file uploading is in process .There are different coloring options for showing the file upload.
  • Green color to indicate the file is uploaded successfully
  • Red color to indicate the file upload is not successful  
Sql server database is used to save the uploaded image by AsynFileUpload control.Here i have used a DataList control to display the uploaded images.In this Data List Control you can create your friends photo gallery like google+ and Facebook. For this application, you have to install AjaxToolkit first on your visual studio.You can install it easily from Here.
There are different concepts that you can implement by using this concepts.
  1. You can create your image gallery by using Grid View and Repeater control also in asp.net application.
  2. You can use  this AsynFileUpload control on your asp.net Form like IBPS.
  3. You can use this concepts in asp.net 3 tier architecture also.
  4. You can save your file path in .mdf database in asp.net
  5. You can use secure connections in your .net applications.
There are some steps to implement this whole concepts as given below:-
Step 1:- First create a table (image_db) with three columns id,image_name and path  as shown below:-

Step 2:- First open your visual studio-->File-->New--> Web Site --> Select ASP.NET Empty Website -->OK --> Open Solution Explorer --> Add a New Page (Default.aspx). 
Step 3:- Now Drag and Drop ToolkitScriptManager, AsyncFileUpload and SqlDataSource controls  from the Toolbox on the page (Default.aspx) as shown below:-

Step 3:- Now Configure your Sql Data source as given in this DOC file.

Note 
  • If you are using this connection string then you have to no need to put connection strings in your web.config file separately .This is automatically added in your web.config file when you finished the configurations.
  • You can use other connection strings also instead of this sql data source.
Step 4:- Now open source file--> drag and drop DataList control and sets its some properties --> drag and drop image control and bind it as given below in codes. 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <br />
        <span class="style1"><strong>How to Upload image files and 
        save it into sql database using Ajax AsyncFileUpload control in asp.net<br />
        </strong>
        </span>
        <span class="style2"><strong><span class="style3">Upload Images</span></strong><span class="style1"><asp:AsyncFileUpload 
            ID="AsyncFileUpload1" runat="server" 
            onuploadedcomplete="Ajax_imageUpload" Height="34px" />
        </span>
        </span>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:masterConnectionString %>" 
            SelectCommand="SELECT * FROM [image_db]"></asp:SqlDataSource>
        <asp:DataList ID="DataList1" runat="server" RepeatColumns="5" 
            RepeatDirection="Horizontal" BackColor="White" Height="226px" 
            Width="838px" BorderColor="#990000" BorderWidth="20px"  >
        <ItemTemplate>
        <table>
        <tr>
        <td>
            <asp:Image ID="Image1" runat="server" Height ="150" Width ="150" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"path")%>'  />
        </td>
        </tr>
        </table>
        </ItemTemplate>           
        </asp:DataList>
    </div>
    </form>
</body>
</html>

Step 5:-  Now press Design from the blew of the page--> You will see following template as shown below:-



Note :-  Here you can see,there are five images displayed horizontally. You can change it according to your requirements with following properties of DataList control .
  • RepeatColumns="5"
  • RepeatDirection="Horizontal"
Step 5:- Now open Solution Explorer Window --> Create a Empty Folder (msdotnet)  as shown below:-

Note :-I  have already set this folder name(msdotnet) for image path in step 6 c# codes .
Step 6:- Now Open Default.aspx.cs file and write the C# codes as given below
using System;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{ //create connection string..
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //generate a method handler press two time tab or generate by the mouse click on that method
            Bind_DatalistItems();
        }
    }
    protected void Ajax_imageUpload(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        try
        {   //first make an Empty variable file_Path 
            string file_Path = string.Empty;
        // create a new string for image path and save the sting path and image in msdotnet folder in your project.
            //guid.NewGuid() is used to generate unique name for each image.
            file_Path = (Server.MapPath("~/msdotnet/") + Guid.NewGuid() + System.IO.Path.GetFileName(e.FileName));
            AsyncFileUpload1.SaveAs(file_Path);
            //add substring in image path
            string file = file_Path.Substring(file_Path.LastIndexOf("\\"));
            //Deletes a specified number of characters form this instance beginning at a specified position
            string file_name = file.Remove(0, 1);
            // STORE complete image path starting with name 'msdonet'into Complete_FilePath VARIABLE 
            string complete_FilePath = "~/msdotnet/" + file_name;
            //open connection..
            con.Open();
            //insert image_name and path in image_db table in your database
            SqlCommand cmd = new SqlCommand("insert into image_db(image_name,path) values(@b,@c)", con);
            cmd.Parameters.AddWithValue("@b", file_name);
            cmd.Parameters.AddWithValue("@c", complete_FilePath);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        finally
        {
            con.Close();
        }
    }
    private void Bind_DatalistItems()
    {
        try
        {
            // first open connection
            con.Open();
            SqlCommand cmd = new SqlCommand("select path from image_db", con);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                DataList1.DataSource = dr;
                DataList1.DataBind();
            }
            else
            {
                DataList1.DataSource = null;
                DataList1.DataBind();
            }
        }
        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        finally
        {
            con.Close();
        }
    }
}

Step 7:-Now Run the application (Press F5)--> Press Browse Button and select the image from your computer Drive--> then you will see following output as shown below:-
Step 8:-Now Open Solution Explorer window --> open msdotnet folder ,you will see that your uploaded image will be saved in this folder as shown below:- 


Step 9:-Now open your Database table(image_db) and you will see ,image_name and image path will be saved in this table as shown below:-

Note - I have used different way to bind the Image in DataList control in Default2.aspx page . This is very easy way to bind the image. You can can download this application from the below link and see default2.aspx page.
For More...
  1. How to create captcha image on asp.net website easily
  2. How to create complete registration and login page in asp.net
  3. How to insert data in database and print the grid view data in asp.net
  4. How to create setup file with database in asp.net
  5. File Handling real concepts with real life example
  6. How to host asp.net website on IIS Server
  7. How to create dll file and use it in asp.net application
  8. Form based Authentication in asp.net
  9. Object Oriented Programming in c# .net with real life examples
  10. How to implement Cookie concepts in asp.net with an example
  11. .NET Complete Interview Questions and Answers With Examples
  12. How to build your own media player and install it on your computer
If you want to Run this application directly on your Visual studio,download it from below link.First Drag and Drop ToolkitScriptManager on Default.aspx page as well as change connection strings also.
Download whole attached file
     Download

0 comments:

Post a Comment

Powered by Blogger.