file extension validation in jQuery

Hello Friends,

Recently one of my project require file extension validation. I am using jquery to achive this. So, i have done it in simple way with jquery as follow

$(function ()
{
   $('#btnSubmit').click(function ()
   {
      var ext = ['jpeg', 'jpg', 'png', 'gif'];
      var file = $("file").val();
      if ($.inArray(file.split('.').pop().toLowerCase(), ext) == -1)
      {
          alert ('Only jpg, png and gif are allowed.');
      }
   }
}

Include HTML as follow.



It is work with jQuery js. So, include jQuery js file. Hope it will help someone!!!!

File Upload plugin with jCrop in c#

Hello Friends,

I want to add jCrop in my previous blog. I have describe how we use jquery file upload plugin in my previous blog. I want to add image crop functionality.

To add crop you need jCrop which is also available in Github from https://github.com/tapmodo/Jcrop or go to http://deepliquid.com/content/Jcrop.html.

First add jquery file upload then add jcrop js and css in your project.





After uploading of image reference image file to “imgCrop”. Here, i have not allow user to resize in crop you can give them by simple allowResize parameter to true same way you can allow reselect too.

Now, add following to html.

        

Add some code to cs file

        protected void btnCrop_Click(object sender, EventArgs e)
        {
            String path = Server.MapPath("~/Files");
            string cropImagePath = "";
            string cropImageName = "";

            string ImageName = hdImageName.value;
            int w = Convert.ToInt32(hdW.Value);
            int h = Convert.ToInt32(hdH.Value);
            int x = Convert.ToInt32(hdX.Value);
            int y = Convert.ToInt32(hdY.Value);

            byte[] CropImage = Crop(path + "\\" + ImageName, w, h, x, y);
            using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
            {
                ms.Write(CropImage, 0, CropImage.Length);
                using (System.Drawing.Image CroppedImage = System.Drawing.Image.FromStream(ms, true))
                {
                    cropImageName = GetPhysicalFileName("c" + ImageName, path);
                    cropImagePath = path + "\\" + cropImageName;
                    CropImage.Save(cropImagePath, CropImage.RawFormat);
                }
            }

            ScriptManager.RegisterStartupScript(this, typeof(Page), new Guid().ToString(), "CloseCrop();", true);
        }

        static byte[] Crop(string tImg, int Width, int Height, int X, int Y)
        {
            try
            {
                using (System.Drawing.Image orgImage = System.Drawing.Image.FromFile(tImg))
                {
                    using (System.Drawing.Bitmap tbmp = new System.Drawing.Bitmap(Width, Height))
                    {
                        bmp.SetResolution(orgImage.HorizontalResolution, orgImage.VerticalResolution);
                        using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(tbmp))
                        {
                            Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                            Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            Graphic.DrawImage(orgImage, new System.Drawing.Rectangle(0, 0, Width, Height), X, Y, Width, Height, System.Drawing.GraphicsUnit.Pixel);
                            MemoryStream ms = new MemoryStream();
                            bmp.Save(ms, orgImage.RawFormat);
                            return ms.GetBuffer();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        protected string GetPhysicalFileName(string fileName, string directoryPath)
        {

            string orgFileName = fileName;
            string phyFileName = fileName;

                if (File.Exists(directoryPath + "\\" + orgFileName))
                {
                    int count = 1;
                    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(orgFileName);
                    string extension = Path.GetExtension(orgFileName);
                    string tempName;

                    while (true)
                    {
                        tempName = fileNameWithoutExt + count.ToString() + extension;

                        if (!File.Exists(directoryPath + "\\" + tempName))
                        {
                            phyFileName = tempName;
                            break;
                        }
                        else
                        {
                            count += 1;
                        }
                    }
                }

            return phyFileName;
        }

You are ready with code. May it will help you.

Example of jQuery File Upload in c#

Hello all,

Today i want to share you example of jQuery File Upload plugin. You can download jQuery file upload plugin from github here.

There are some example provided by them in .net also. But my requirement is not set with that so, i have prepared one example.

First include some necessary files like following.













Here you can exclude ifrmae-transport if you are not using cross domain. Also, process is used for processing and validate use to validate file.

Now, initialize the fileupload

        $(function ()
        {
            var tbodyList = "";
            var trListRowClone = "";
            'use strict';

            var url = '/Handler/Handler.ashx';
            // Initialize the jQuery File Upload widget:
            $('#fileupload').fileupload({
                url: url,
                dataType: 'text',
                autoUpload: true,
                acceptFileTypes: /(jpg)|(jpeg)|(png)|(gif)|(pdf)$/i, // Allowed file types
                progress: function (e, data)
                {
                    var bar = $('.bar');
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    var percentVal = progress + '%';
                    bar.width(percentVal);
                },
                done: function (e, data)
                {
                    var newRow = trListRowClone.cloneNode(true)
                    newRow.physicalFileName = this.files[0].name; // data
                    newRow.cells[0].getElementsByTagName("span")[0].childNodes[0].data = this.files[0].name;
                    tbodyList.appendChild(newRow);
                }
            });            
        });

Now, we write html

        
File-Name  

The Last thing is handler.


public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        
        foreach (string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            string FileName = string.Empty;
            if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
            {
                string[] files = hpf.FileName.Split(new char[] { '\\' });
                FileName = files[files.Length - 1];
            }
            else
            {
                FileName = hpf.FileName;
            }
            if (hpf.ContentLength == 0)
                continue;
            
            string savedFileName = context.Server.MapPath("~/Your-folder-name/" + FileName);
            hpf.SaveAs(savedFileName);

            context.Response.Write(FileName);
            context.Response.StatusCode = 200;
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

Now, everything is ready. You can find your file at “your-folder-name”. Enjoy!!!

how to call server side button event in jquery dialog

Hi All,

Generally we are using jquery modal dialog for modal popup window in our application.

Sometimes we need to call server side button event from modal popup window and it creates problem for us.

Today I am going to describe how can we call asp.net button event from jquery modal popup window.

lets take an simple example:

Asp.Net Button Code:



Jquery Modal Popup Script:


 

Code Behind Button Event:


protected void Button1_Click(object sender, EventArgs e)
{
    //your button click event code comes here
    //you can do anything here
}

Please note that you need to add jquery modal popup related script reference in your code.

How to hide close button from title bar in jquery UI Dialog

Hi Friends,

Today I have a requirement to hide the jquery ui dialog close button from title bar.

we can do this easily by using jquery css but this will hide globally from our project.

I want to hide it in just one page and other page will show the button when user opens the modal dialog.

I have used below code for above functionality.



    
    
    

Here, I have used jquery function on open event for hiding a close button; see the below line
open: function (event, ui) { $(this).closest(‘.ui-dialog’).find(‘.ui-dialog-titlebar-close’).hide(); }, which fulfill my requirement.

This is html part of my page :


Sample demo of jquery modal popup

click here top open dialog box

Sample content of modal popup window comes her

This is sample jquery modal popup window...

Design this as per your requirement


This is online demo for your help, jquery_title

Hope this will help you !!!

Increase textbox width onclick by jQuery

Hello Friends,

Today i want to share one small example of increase textbox width onclick by jquery. Actually to increase width of textbox we will animate textbox with jquery.

We will use following code to animate textbox.

        $(document).ready(function ()
        {
            $('#txtSearch').focus(function ()
            {
                /*to make flexible, store the current width in an attribute*/
                $(this).attr('width-default', $(this).width());
                $(this).animate({ width: 250 }, 'slow');
            }).blur(function ()
            {
                /* restore the original width */
                var w = $(this).attr('width-default');
                $(this).animate({ width: w }, 'slow');
            });
        });

Replace txtSearch with your textbox name and also change width in animate as appropriate your width. Enjoy!!!

How to open and close jquery UI dialog box

Hi Friends,

Today I am going to represent how to use jquery dialog box in html page.

In this article I will describe, How to open and close jQuery UI Dialog box on click of anchor tag.

Add below code in your html header section







I have added online jquery script reference. you can download it from those URL.

Now add below code in html body section


Sample demo of jquery modal popup

click here to open dialog box

Sample content of modal popup window comes her

This is sample jquery modal popup window...

Design this as per your requirement


That’s it.

Click here for online demo of jquerymodal