Sunday, December 24, 2017

Upload file’s on button click using Dropzone JS plugin in asp.net application

In this article I am going how to upload file’s on button click using Dropzone JS plugin in asp.net application.

Description:
I want to upload multiple files using select or drag & drop in asp.net application on submit button click. I am using Dropzone js to upload file.

Implementation:
I have created a table GalleryImages to save file’s name and path.

Id
int
Filename
varchar(MAX)
FilePath
varchar(MAX)
Is_Deleted
bit

Create procedure to save detail to database table.

Create proc InsertGalleryImages
(
@Filename varchar(max),
@filepath varchar(max)
)
as begin
INSERT INTO [GalleryImages]
           ([Filename]
           ,[FilePath]
           )
     VALUES
           (@Filename,@filepath)
end


Now download the Dropzone js. Add a webform to project. Add the reference of CSS and js to newly added webform.

HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Select or drag & drop upload multiple files in asp.net</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
    <link href="css/dropzone.css" rel="stylesheet" />
    <script src="js/dropzone.js"></script>
     <script type="text/javascript">
         $(document).ready(function () {
             Dropzone.autoDiscover = false;
             var myDropzone = new Dropzone("#dZUpload",{
                 url: "FileUploader.ashx",
                 autoProcessQueue: false,
                //upload more than 2 files by Dropzone.js with button
                 parallelUploads: 6,
                 //File size
                 maxfilesize: 100,
                 //Number of files
                 maxFiles: 6,
                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");
                }
            });
             $('#btnsubmit').on('click', function (e) {
                myDropzone.processQueue();

alert("File's uploaded successfully");
            });
        });
        </script>

</head>
<body>
    <form id="form1" runat="server">
     <div align="center">

        <div id="dZUpload" style="width:800px; margin:0 auto;" class="dropzone" >
        <div  class="dz-default dz-message">
            <br />
            <br />
            <br /><br />
           Drag & Drop files here
        </div>
    </div>
         <br />
         <asp:Button ID="btnsubmit" runat="server" Text="Save Files" />
    </div>
    </form>
    <style>
        .dz-default{
            background-image:url(images/img-upload.png);
            background-repeat:no-repeat;
            background-position: center;
        }
    </style>
</body>
</html>


Add Generic handler to application.

C# code
<%@ WebHandler Language="C#" Class=" FileUploader" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class Uploader : IHttpHandler {   
  
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
            context.Response.ContentType = "text/plain";
            string FilesPath = HttpContext.Current.Server.MapPath("~/images/");
                string[] files;
                string uploadedfiles = "";
                foreach (string s in context.Request.Files)
                {
                    HttpPostedFile file = context.Request.Files[s];
                    int fileSizeInBytes = file.ContentLength;
                    string fileName = file.FileName;
                    string fileExtension = file.ContentType;
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        fileExtension = System.IO.Path.GetExtension(fileName);
                        files = System.IO.Directory.GetFiles(FilesPath);
                        uploadedfiles = Guid.NewGuid() + fileName;
                        string path = HttpContext.Current.Server.MapPath("~/images/") + uploadedfiles;
                        file.SaveAs(path);
                        SqlCommand cmd = new SqlCommand("InsertGalleryImages", con);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Filename", uploadedfiles);
                        cmd.Parameters.AddWithValue("@filepath", "~/images/" + uploadedfiles);
                        con.Open();
                        cmd.ExecuteNonQuery();
                       // con.Close();
                    }
                }
                context.Response.Write(uploadedfiles);
        }
        catch (Exception ex)
        {

            context.Response.Write("ERROR: " + ex.Message);
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

VB.Net Code
<%@ WebHandler Language="VB" Class=" FileUploader " %>

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

Public Class Handlervb : Implements IHttpHandler
   
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Try
            Dim con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
            context.Response.ContentType = "text/plain"
            Dim FilesPath As String = HttpContext.Current.Server.MapPath("~/images/")
            Dim files As String()
            Dim uploadedfiles As String = ""
            For Each s As String In context.Request.Files
                Dim file As HttpPostedFile = context.Request.Files(s)
                Dim fileSizeInBytes As Integer = file.ContentLength
                Dim fileName As String = file.FileName
                Dim fileExtension As String = file.ContentType
                If Not String.IsNullOrEmpty(fileName) Then
                    fileExtension = System.IO.Path.GetExtension(fileName)
                    files = System.IO.Directory.GetFiles(FilesPath)
                    uploadedfiles = Guid.NewGuid().ToString() & fileName
                    Dim path As String = HttpContext.Current.Server.MapPath("~/images/") & uploadedfiles
                    file.SaveAs(path)
                    Dim cmd As SqlCommand = New SqlCommand("InsertGalleryImages", con)
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.Parameters.AddWithValue("@Filename", uploadedfiles)
                    cmd.Parameters.AddWithValue("@filepath", "~/images/" & uploadedfiles)
                    con.Open()
                    cmd.ExecuteNonQuery()
                End If
            Next

            context.Response.Write(uploadedfiles)
        Catch ex As Exception
            context.Response.Write("ERROR: " & ex.Message)
        End Try
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class



No comments:

Post a Comment