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!!!!

How to download file in asp.net

Hi Friends,

Today I am going to describe file download functionality in asp.net.

we can download file using different methods in asp.net.

Today I am going to describe Response.TransmitFile method of asp.net

Lets see how can we do it


public void Downloadfile(string fileName, string filePath )
{
    FileInfo file = new FileInfo(filePath + "\\" + fileName);
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.TransmitFile(filePath + "\\" + fileName);
    Response.Flush();
    Response.End(); 
}

You can download file easily by using above function.
Note:
1. You need to pass fileName and filePath parameters
2. Here, I have used general content type “application/octet-stream”. Change it as per your requirement
3. Add reference for System.IO

Hope this will help you !!!!

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!!!