Home > ASP.Net, Jquery > Use JQuery with FileUpload

Use JQuery with FileUpload


Hi

try this example to use JQuery with FileUpload

Step1 :- Open Visual Studio 2008 and Create new website

Step2 :- Download the following  jQuery 1.3.2 , jQuery VS 2008 Doc and the Multiple File Upload PlugIn and Create a “Scripts” folder in the Solution Explorer of your project

Step3 :- Add web page and add this script in the <head> section of your page as shown below

<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
      <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>

 Step4 :- From ToolBox drag and drop an ASP.NET FileUpload control and Button Control  and Lable Control to the page.

<asp:FileUpload ID="FileUpload1" runat="server" 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="">

 Step5 :- In Code behind add the following code


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.";
        }
    }

    private string GetFileExtension(string filePath)
    {
        FileInfo fi = new FileInfo(filePath);
        return fi.Extension;
    }
  
    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();
    }

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

    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;
    }

    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;
    }

    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;
    }

and don’t forget to use the following NameSpaces

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

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net, Jquery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: