File or Image upload in ASP.NET C# Using Dropzone JQuery and JavaScript

File  upload in ASP.NET  C# Using Dropzone JQuery and JavaScript

Asp.net Image uploading drag and drop with in the DropZone Multiple file Uploading Using JQuery and Javascript without user action.

DEMO




                                DOWNLOAD

HTML  CODING



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageUpload.aspx.cs" Inherits="ImageUpload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>


     <script src="DropzoneJs_scripts/jquery.min.js"></script>
    <script src="DropzoneJs_scripts/dropzone.js"></script>
    <link href="DropzoneJs_scripts/dropzone.css" rel="stylesheet" />

       
    <script type="text/javascript">


        $(document).ready(function () {
            
            Dropzone.autoDiscover = false;
            var username = $('#<%=lbtUsername.ClientID %>').text().toString();
            $("#dZUpload").dropzone({
                url: "Uploader.ashx?username=" + username.toString(),
                maxFiles: 5,
                addRemoveLinks: true,
                success: function (file, response) {
                    var imgName = response;
                    file.previewElement.classList.add("dz-success");
                    console.log("Successfully uploaded :" + imgName);
                },
                error: function (file, response) {
                    file.previewElement.classList.add("dz-error");
                }
            });
        });
        </script>

   

</head>
<body>
    <form id="form1" runat="server">
    <div align="center">
  <asp:LinkButton ID="lbtUsername" runat="server" Font-Names="Verdana" Text="Dotnetdrizzles@gmail.com" Font-Size="Large" Font-Underline="True" ForeColor="#FF0066"></asp:LinkButton>
        <div id="dZUpload" style="width:500pxmargin:0 auto;" class="dropzone" >
        <div  class="dz-default dz-message">
           Drag & Drop Images [5] here.
            <br />
        </div>
    </div>
   
    </div>
    </form>
</body>
</html>



Database Table


CREATE TABLE [dbo].[imagereg] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [imgname]   VARCHAR (50)  NOT NULL,
    [imgpath]   NVARCHAR (50) NOT NULL,
    [username]  VARCHAR (50)  NOT NULL,
    [imgheight] VARCHAR (50)  NOT NULL,
    [imgwidth]  VARCHAR (50)  NOT NULL,
    [imgsize]   VARCHAR (50)  NOT NULL,
    [date1]     VARCHAR (50)  NOT NULL,
    [month1]    VARCHAR (50)  NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


Uploader.ashx

<%@ WebHandler Language="C#" Class="Uploader" %>

using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.SqlClient;

public class Uploader : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
    try
    {
        context.Response.ContentType = "text/plain";
        string id = context.Request.QueryString["username"].ToString();
        string username = id.Substring(0, id.IndexOf("@"));
       

        if (context.Request.QueryString["username"].ToString() != "")
        {

            string dirFullPath = HttpContext.Current.Server.MapPath("~/IMAGES/");
            string[] files;
            int numFiles;
          
            string str_image = "";
            if ((context.Request.QueryString["username"].ToString() != ""))
            {
               
                HttpFileCollection fil = context.Request.Files;
                for (int s = 0; s < fil.Count; s++)
                {
                    HttpPostedFile file = context.Request.Files[s];
                    string fileName = file.FileName;
                    string fileExtension = file.ContentType;
                    files = System.IO.Directory.GetFiles(dirFullPath);
                    numFiles = files.Length;
                    numFiles = numFiles + 1;
                  

                    /////// Image Path Get ///////

                    fileExtension = Path.GetExtension(fileName);
                    str_image = username + "_" + numFiles.ToString() + fileExtension;

                    /////// Image Path Get End ///////

                    string pathToSave = HttpContext.Current.Server.MapPath("~/IMAGES/") + str_image;
                    file.SaveAs(pathToSave);
                   
                    // img size  ////
                    System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream);
                    int height = img.Height;
                    int width = img.Width;
                    decimal size = Math.Round(((decimal)file.ContentLength / (decimal)1024), 2);
                   
                    // image size end   //
                   
                    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
                    con.Open();
                    DateTime dt = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                    string month = dt.Month.ToString() + "/" + dt.Year.ToString();
                    string date = dt.Day.ToString() + "/" + dt.Month.ToString() + "/" + dt.Year.ToString();
                    SqlCommand cmd = new SqlCommand("insert into imagereg(imgname,username,imgpath,imgheight,imgwidth,imgsize,date1,month1) values('" + str_image.ToString() + "','" + id.ToString() + "','" + "~/IMAGES/" + str_image.ToString() + "','"+height.ToString()+"','"+width.ToString()+"','"+size.ToString()+"','"+date.ToString()+"','"+month.ToString()+"')", con);
                    cmd.ExecuteNonQuery();
                  
                    context.Response.Write(str_image);

                }

            }
        }
    }
    catch (Exception ex)
    {

        context.Response.Write("ERROR: "+ex.Message);
    }
    }


  

    public bool IsReusable {
        get {
            return false;
        }


    }

}


First - Add New Webform and Add new Generic Handler.ashx 





Next -add to Dropzone Js file to Folder than call the javascript file below like

Next - Username pass to the Uploader.ashx file using javascript and jquery

next - add allow file size to uploading max 5 (Required)





<div> tag add dropzone size and class






Next - Drop zone <div> below like Showing and add username 





Next - add the namespaces & separate the username using substring




Next - retrive server path and increment the username(Imagename) from server folder and get image path and save to the server folder





Next - get image width and height and size  insert to the Database 





Image path to save the database below likes





Next all informations save to the database 



4 comments:

  1. this article,how to remove path image folder ?
    thanks.

    ReplyDelete
  2. Great. It's working fine. But how to remove files from server? It´s possible an example. Thank you.

    ReplyDelete
  3. Nice post ! Thanks for sharing valuable information with us. Keep sharing..
    AngularJS Online Training Bangalore

    ReplyDelete