Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Archive for October, 2009

Multiple File Upload using JQuery

Posted by Ramani Sandeep on October 28, 2009

Introduction

In this article I have explained how to upload multiple files using file upload control. I have used jQuery plugin for uploading multiple files.

I have also explained how to check for file type, file maximum size limit using jQuery & also using server side validation code.

Download the Following Files

Namespace used

using System.Security.Cryptography;
using System.Text;
using System.IO;

Step 1: Include the jQuery Files needed on the page.

Assuming you have downloaded these files, create a reference to these files in the <head> section of your page as shown below:

  <head id="Head1" runat="server">
        <title>Multiple File Upload using JQuery</title>
        <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="Scripts/jquery.MultiFile.js" type="text/javascript">
        </script>
    </head>

Step 2: Add File Upload Control & Button on the Page.

 <asp:FileUpload ID="FileUpload1" runat="server" class="multi" accept="gif|jpeg|bmp|png|jpg"
        maxlength="5" />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" />
    <br />
    <asp:Label ID="lblMsg" runat="server" Text="">\
    </asp:Label>

class=”multi” is used to specify that user can select multiple files.
maxlength property specify that user can upload maximum 5 files not more than that.
accept property used to restrict user to upload only certain type of file only.

Step 3: Double click on Upload Button & Write the code that is used to upload files.

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (ServerSideValidation() == true)
        {
            string SavePath, Msg = null;

            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    SavePath = ConfigurationManager.AppSettings["PatientPhotoImages"].ToString()
                        + GetUniqueKey() + GetFileExtension(hpf.FileName);
                    hpf.SaveAs(Server.MapPath(SavePath));
                    //SavePath can be saved in DB.
                    Msg += GetFileName(hpf.FileName.ToString()) + " , ";
                }
            }
            lblMsg.Text = Msg + " Uploaded Successfully.";
        }
    }

Step 4: Write the private function which helps to Upload files.

This function helps to extract file extension from the fileName.

 private string GetFileExtension(string FileName)
    {
        char saperator = '.';
        string[] temp = FileName.Split(saperator);

        return "." + temp[1].ToString();
    }

OR

private string GetFileExtension(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Extension;
    }

This function helps to get Unique Key, which is used to save files on server with different name that does not collied with each other.

 private string GetUniqueKey()
    {
        int maxSize = 8;
        char[] chars = new char[62];
        string a;

        a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

        chars = a.ToCharArray();

        int size = maxSize;
        byte[] data = new byte[1];

        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();

        crypto.GetNonZeroBytes(data);
        size = maxSize;
        data = new byte[size];
        crypto.GetNonZeroBytes(data);
        StringBuilder result = new StringBuilder(size);

        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length - 1)]);
        }

        return result.ToString();
    }

This function help to get Filename from the filepath.

 private string GetFileName(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Name;
    }

Step 5: Add Server Side Validation Code

This is the function which is used to validate files that user wants to upload. If the client side validation does not work, this code will help us to identify the invalid files.

Validation rules like whether file type is correct or not, file size is valid or not.

If you do not want to validate the files on server side, you can ignore this code. But I prefer to use it.

 private bool ServerSideValidation()
    {
        string errorMsg = string.Empty, temp = null;
        bool errorFlag = true;

        // Get the HttpFileCollection
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                temp = ValidateImage(hpf);
                if (temp != null)
                {
                    errorMsg += GetFileName(hpf.FileName.ToString()) + " has error : " + temp;
                    temp = null;
                }
            }
        }

        if (errorMsg != "")
        {
            lblMsg.Text = errorMsg;
            errorFlag = false;
        }
        return errorFlag;
    }

This function used to check file type & file size. If file is invalid than it will return error message.

 private string ValidateImage(HttpPostedFile myFile)
    {
        string msg = null;
        int FileMaxSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileUploadSizeLimit"].ToString());
        //Check Length of File is Valid or Not.
        if (myFile.ContentLength > FileMaxSize)
        {
            msg = msg + "File Size is Too Large.";
        }
        //Check File Type is Valid or Not.
        if (!IsValidFile(myFile.FileName))
        {
            msg = msg + "Invalid File Type.";
        }
        return msg;
    }

This function is used to check whether the file that user want to upload is valid file type or not.

private bool IsValidFile(string filePath)
    {
        bool isValid = false;

        string[] fileExtensions = { ".BMP", ".JPG", ".PNG", ".GIF", ".JPEG" };

        for (int i = 0; i < fileExtensions.Length; i++)
        {
            if (filePath.ToUpper().Contains(fileExtensions[i]))
            {
                isValid = true; break;
            }
        }
        return isValid;
    }

Conclusion:

This code is complete solution that helps to upload multiple file using File Upload with jQuery plugin. I was always in a need of such code in my route work so I decided to write the code that helps others also.

Hope this will help !!!
Jay Ganesh

kick it on DotNetKicks.com Shout it

Posted in ASP.NET, JQuery | Tagged: , , , , | 43 Comments »

ASTreeView – A Powerful ASP.Net TreeView Control

Posted by Ramani Sandeep on October 23, 2009

ASTreeView is a powerful treeview with drag drop, ajax loading, context menu, xml import/export, checkbox, selection, add/editing/deleting nodes with ajax.

ASTreeView is developed on .NET framework 2.0. Demo project is a Visual Studio 2005 project.

ASTreeView is FREE! That means you can use it anywhere!

for more detail : click here

Posted in ASP.NET, ASP.NET Ajax | Tagged: , , | 1 Comment »

Ebook : 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls

Posted by Ramani Sandeep on October 14, 2009

hi readers ,

here is a very useful book that explore the jQuery usage with ASP.NET Controls. This is very handy book for the web developer who uses jQuery along with ASP.NET.

It helps to enhance your web experience & better understand how/where/when to use jQuery with ASP.NET Controls.

read more : here

read the content : here

Posted in ASP.NET, ASP.NET 3.5, JQuery | Tagged: , , , | 8 Comments »

Watch the Video of Luke Hoban & Luca Bolognese

Posted by Ramani Sandeep on October 14, 2009

Linq to SQL by Luca Bolognese

Luca Bolognese is the Principal Program Manager Lead on the C# team. His talk on LINQ to SQL endows developers with the knowledge necessary to wield the tools that drive data driven application development under C# 3.0. A consummate speaker, Luca skillfully guides his audience through the elements that comprise LINQ to SQL development.

watch the video here

An In-Depth Look at C# 3.0 by Luke Hoban

Luke Hoban was the PM who drove the development of LINQ to Objects, and the man who created the now famous implementation of a ray tracer in a single, very long, LINQ query expression. He is now focusing his efforts on F#. By listening to his talk on C# 3.0 features you will get a chance to see a detailed and specific analysis of how LINQ works. Listening to him give this talk marked a turning point in my understanding of LINQ. For the first time I understood how the team folded extension methods and query expressions together to create the marvelously supple and deceptively simple syntax that we know as LINQ.

watch the video here

Posted in ASP.NET 3.5, C# 3.0 | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 317 other followers