Sunday, June 16, 2013

How to upload multiple files using AjaxFileUpload and save path to Database in Asp.net

Introduction: In this post I will explain how we can upload the multiple files and save their path to Database using AjaxFileUpload control in Asp.net.
AjaxFileUpload

Description:
In last article I explained How to install Ajax controlToolkit in Visual Studio.  I have created a table IMAGE_PATH. Here IMAGE_ID is primary key.
IMAGE_PATH
int
IMAGE_PATH
varchar(MAX)

Add a new webform to project. Drag and drop the ScriptManager from Ajax Extensions. After that take the AjaxFileUpload control from Toolbox as shown below:
<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="AjaxFileUpload1_UploadComplete1"/>

Note: we can validate the uploaded file via their extension using AllowedFileTypes Property of AjaxFileUpload control.


Example:
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server" AllowedFileTypes="jpg,jpeg,png,gif,bmp,doc,docx" OnUploadComplete="AjaxFileUpload1_UploadComplete1"/>

Now go to AjaxFileUpload control’s Events and double click on UploadComplete and write the following code (.aspx.cs):

using System.Data.SqlClient;
using System.Configuration;
using System.Data;


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

protected void AjaxFileUpload1_UploadComplete1(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string filepath = (Server.MapPath("~/Images/") +Guid.NewGuid()+ System.IO.Path.GetFileName(e.FileName));
        AjaxFileUpload1.SaveAs(filepath);
        string fl = filepath.Substring(filepath.LastIndexOf("\\"));
        string[] split = fl.Split('\\');
        string newpath = split[1];
        string imagepath = "~/Images/" + newpath;
        string Insert = "Insert into IMAGE_PATH (IMAGE_PATH) values (@IMAGE_PATH)";
        SqlCommand cmd = new SqlCommand(Insert, con);
        cmd.Parameters.AddWithValue("@IMAGE_PATH", newpath);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
        cmd.Dispose();

    }

In VB

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

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

    Protected Sub AjaxFileUpload1_UploadComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
        Dim filepath As String = (Server.MapPath("~/Images/") & Convert.ToString(Guid.NewGuid()) + System.IO.Path.GetFileName(e.FileName))
        AjaxFileUpload1.SaveAs(filepath)
        Dim fl As String = filepath.Substring(filepath.LastIndexOf("\"))
        Dim split As String() = fl.Split("\"c)
        Dim newpath As String = split(1)
        Dim imagepath As String = "~/Images/" & newpath
        Dim Insert As String = "Insert into IMAGE_PATH (IMAGE_PATH) values (@IMAGE_PATH)"
        Dim cmd As New SqlCommand(Insert, con)
        cmd.Parameters.AddWithValue("@IMAGE_PATH", newpath)
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
        cmd.Dispose()
    End Sub

Now run the project and check the result.

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.

3 comments:

  1. This approach works well for a few files, but how about a quantity >100?

    Just to check what are the resource costs involved when uploading , say 200 files, using this approach? Because I am currently looking at using this control to upload files to a folder in batch but I really don't want to have to open and close a SQL connection for each file (but I am not sure how it can be done because the onUploadcomplete is called for each file uploaded and the page does not seem to keep the variables used in one upload for the next - seems every variable is cleared).

    ReplyDelete
  2. Anonymous is right. That control is useless when it comes to uploading 100+ pictures - the onuploadcomplete will get called for "EACH" file uploaded.

    ReplyDelete
  3. Turkish letters in file names becomes a problem. How do we handle this.

    ReplyDelete