Thursday, August 1, 2013

Handler.ashx with uploadify.js (jQuery File Uploader Plugin) in ASP.NET (C#)

You can download this plugin from here : http://www.uploadify.com/download/

...WebForm.aspx

<script type="text/javascript" src="js/jquery-1.4.1.js"></script>
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.uploadify.js"></script>
<script type="text/javascript">
      $(document).ready(function () {
        $('#file_upload').uploadify({
            'multi': true,
            'auto': false,
            'swf': 'swf/uploadify.swf',
            'uploader': 'UploadHandler.ashx',
            'fileTypeDesc': 'Image Files',
            'fileTypeExts': '*.gif; *.jpg; *.png',
            'fileSizeLimit': '1024KB',
            'uploadLimit': 3,
            'successTimeout': '5',
            'onUploadSuccess': function (file, data, response) {
              alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
                   }
        })
    });
</script>
<body>
<h3>Multiple File Upload Example</h3>
<div id="test">
  <input type="file" name="file_upload" id="file_upload" />
  <br /> 
<a id="btnupload"  href="javascript:$('#file_upload').uploadify('upload','*')">Upload Files</a>
 <a id="btnCancelUpload"  href="javascript:$('#file_upload').uploadify('cancel','*')" >Cancel Upload </a>
 </div>
</body>

...UploadHandler.ashx

<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.IO;
public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Random rnd = new Random();
        string path = "~/UploadFiles/";
        String filename = HttpContext.Current.Request.Headers["X-File-Name"];
        if (string.IsNullOrEmpty(filename) && HttpContext.Current.Request.Files.Count <= 0)
        {
            context.Response.Write("{success:false}");
        }
        else
        {
            string mapPath = HttpContext.Current.Server.MapPath(path);
            if (Directory.Exists(mapPath) == false)
            {
                Directory.CreateDirectory(mapPath);
            }
            if (filename == null)
            {
                //This work for IE
                try
                {
                    HttpPostedFile uploadedfile = context.Request.Files[0];
                    filename = uploadedfile.FileName;
                    string strExtension = Path.GetExtension(filename).ToLower();
                    filename = filename.Substring(0, filename.Length - strExtension.Length);
                    filename = filename + '_' + rnd.Next(111111, 999999).ToString() + strExtension;                    
                    uploadedfile.SaveAs(mapPath + "\\" + filename);
                    FileStream fs = new FileStream(mapPath + "\\" + filename, FileMode.Open);
                    mapPath = mapPath.Replace(HttpContext.Current.Server.MapPath("~/"), "");
                    mapPath = mapPath.Replace("\\", "/");
                    mapPath = mapPath.Replace("%", "-");
                    mapPath = mapPath.Replace("#", "-");
                    context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + mapPath + filename + "\"}");
                }
                catch (Exception)
                {
                    context.Response.Write("{success:false}");
                }
            }
            else
            {
                //This work for Firefox and Chrome.
                filename = filename.Replace("%20", " ");
                string strExtension = Path.GetExtension(filename).ToLower();
                filename = filename.Substring(0, filename.Length - strExtension.Length);
                filename = filename + '_' + rnd.Next(111111, 999999).ToString() + strExtension;
                FileStream fileStream = new FileStream(mapPath + "\\" + filename, FileMode.OpenOrCreate);
                try
                {
                    Stream inputStream = HttpContext.Current.Request.InputStream;
                    CopyStream(inputStream, fileStream);
                    mapPath = mapPath.Replace(HttpContext.Current.Server.MapPath("~/"), "");
                    mapPath = mapPath.Replace("\\", "/");
                    mapPath = mapPath.Replace("%", "-");
                    mapPath = mapPath.Replace("#", "-");
                    context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + mapPath + filename + "\"}");
                }
                catch (Exception)
                {
                    context.Response.Write("{success:false}");
                }
                finally
                {
                    fileStream.Close();
                }
            }
        }
    }  
    public static long CopyStream(Stream source, Stream target)
    {
        const int bufSize = 0x1000;
        byte[] buf = new byte[bufSize];
        long totalBytes = 0;
        int bytesRead = 0;
        while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
        {
            target.Write(buf, 0, bytesRead);
            totalBytes += bytesRead;
        }
        return totalBytes;
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

No comments:

Post a Comment