Thursday, August 19, 2010

How to upload multiple files using jQuery

‘How to handle multi file upload?’ is a frequently asked a question through the web developing community. There are numerous solutions being published. In this blog I have posted another post to demonstrate how to upload multiple files at the same time using file list control like asp.net DropDownList control. However this post aims to answer the same question .using third party plug-in called file uploadify. This example uses JQuery.

Demo


Markup
<asp:FileUploadField 
    runat="server" 
    ID="fufFileUpload" 
    Label="Select a file"
    IsMulti="true" 
    AllowedFileTypes="*.jpg;*.png;*.gif" 
    FileDescription="Image Files" 
    OnCompleteFunction="OnComplete" 
    OnErrorFunction="OnError" 
    OnSelectFunction="OnSelect" 
    MaxFileSize="0.5" 
    Auto="false" />

Download Source
Download Binay
WebField BaseClass
Resource Manager Helper Class

Java script events:
function OnSelect(event, queueID, fileObj) {
    if (!$.browser.mozilla) {
        alert("File Name: " + fileObj.name);
        alert("File Size: " + fileObj.size + " KB");
        alert("File Creation Date: " +
            fileObj.creationDate.date + "/" +
            fileObj.creationDate.month + "/" +
            fileObj.creationDate.fullYear + " " +
            fileObj.creationDate.hours + ":" +
            fileObj.creationDate.minutes + ":" + 
            fileObj.creationDate.seconds);
        alert("File Modificaiton Date: " +
            fileObj.modificationDate.date + "/" +
            fileObj.modificationDate.month + "/" +
            fileObj.modificationDate.fullYear + " " +
            fileObj.modificationDate.hours + ":" +
            fileObj.modificationDate.minutes + ":" + 
            fileObj.modificationDate.seconds);
        alert("File Type: " + fileObj.type);
    }
    return true;
}
function OnError(event, queueID, fileObj, errorObj) {
    alert("On Error");
    return true;
}
function OnComplete(event, queueID, fileObj, response, data) {
    alert("On Complete");
    return true;
}

Web.config
IIS 7:
<handlers>
  <add name="FileUploadHandler" path="UploadHandler.ashx" verb="*"
       type="WebSphere.Web.UI.Fields.UploadHandler"
       resourceType="Unspecified" preCondition="integratedMode"/>
</handlers>
IIS6:
<httpHandlers>
  <add verb="GET" path="UploadHandler.ashx"
       type="WebSphere.Web.UI.Fields.UploadHandler, WebSphere.Web.UI.Fields"/>
</httpHandlers>

Control Implementation:
public class FileUploadField : WebField
{
    #region Attributes
 
    private string script = @"
        $(document).ready(function () {{
            $('#{0}').uploadify({{
                'uploader': '{1}',
                'expressInstall': '{2}',
                'script': '{3}?{4}={5};{6}',
                'folder': '{7}',
                'cancelImg': '{7}',
                'queueID': '{8}',
                'multi': {9},
                'buttonImg' : '{10}',
                'height' : {11},
                'width' : {12},
                'auto' : {13},
                {14}
                'onSelect': function (event, queueID, fileObj) {{
                    {15}
                    {16}
                    {17}(event, queueID, fileObj);
                }},
                'onError': function (event, queueID, fileObj, errorObj) {{
                    {18}(event, queueID, fileObj, errorObj);
                }},
                'onComplete': function (event, queueID, fileObj, response, data) {{
                    {19}(event, queueID, fileObj, response, data);
                }}
            }});
        }});
    ";
    private string checkFileTypeFunction = @"
                    var fileTypes = '{0}'.split(';');
                    var isValid = false;
                    for(i=0;i<fileTypes.length;i++){{
                        var ext = fileTypes[i].replace('*','').toLowerCase();
                        if(isValid = fileObj.type.toLowerCase() == ext) break;
                    }}
                    if(!isValid){{
                        alert('{1}');
                        this.uploadifyCancel(event, queueID, fileObj, false);
                    }}
    ";
    private string sizeValidationFunction = @"
                    if(fileObj.size/(1024 * 1024) > {0}){{
                        alert('{1}');
                        this.uploadifyCancel(event, queueID, fileObj, false);
                    }}
    ";
 
    #endregion
 
    #region Properties
 
    public bool IsMulti { getset; }
    public string UploadFolder { getset; }
    public string QueueId { getset; }
    public double MaxFileSize { getset; }
    public string UploadHandler { getset; }
    public int BrowseButtonHeight { getset; }
    public int BrowseButtonWidth { getset; }
    public string BrowseImage { getset; }
    public string CancelAllImage { getset; }
    public string CancelImage { getset; }
    public string UploadImage { getset; }
    public string AllowedFileTypes { getset; }
    public string FileDescription { getset; }
    public string InvalidFileTypeErrorMessage { getset; }
    public string InvalidFileSizeErrorMessage { getset; }
    public bool Auto { getset; }
    public string OnErrorFunction { getset; }
    public string OnSelectFunction { getset; }
    public string OnCompleteFunction { getset; }
 
    #endregion
 
    #region Methods
 
    public FileUploadField()
    {
        this.Initialize();
    }
    private void Initialize()
    {
        this.IsMulti = false;
        this.UploadFolder = "Uploads";
        this.QueueId = "fileQueue";
        this.UploadHandler = "UploadHandler.ashx";
        this.BrowseButtonHeight = 20;
        this.BrowseButtonWidth = 22;
        this.FileDescription = "Selected Files";
        this.InvalidFileTypeErrorMessage = "Invalid file type";
        this.InvalidFileSizeErrorMessage = "File is too large";
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        string cancelImage = this.ResolveUrl(string.IsNullOrEmpty(this.CancelImage) ? 
            ResourceManager.GetResourcePath("FileUploadField.Cancel.png", 
            this.GetType(), this.Page) : this.CancelImage);
        string browseImage = this.ResolveUrl(string.IsNullOrEmpty(this.BrowseImage) ? 
            ResourceManager.GetResourcePath("FileUploadField.Browse.png", 
            this.GetType(), this.Page) : this.BrowseImage);
        string typeValidator = string.Empty;
        if (!string.IsNullOrEmpty(this.AllowedFileTypes))
        {
            typeValidator = @"
                'fileDesc' : '{0}({1})',
                'fileExt' : '{1}',
            ";
            typeValidator = string.Format(typeValidator, this.FileDescription, this.AllowedFileTypes);
        }
        script = string.Format(this.script,
            this.ClientID,
            this.ResolveUrl(ResourceManager.GetResourcePath("FileUploadField.Uploadify.swf", 
                this.GetType(), this.Page)),
            this.ResolveUrl(ResourceManager.GetResourcePath("FileUploadField.ExpressInstall.swf", 
                this.GetType(), this.Page)),
            string.Concat(this.RootUrl, this.UploadHandler),
            QueryParameters.Params,
            this.MaxFileSize,
            this.UploadFolder,
            cancelImage,
            this.QueueId.Equals("fileQueue") ? string.Concat(this.ClientID, this.QueueId) : this.QueueId,
            this.IsMulti.ToString().ToLower(),
            browseImage,
            this.BrowseButtonHeight,
            this.BrowseButtonWidth,
            this.Auto.ToString().ToLower(),
            typeValidator,
            !string.IsNullOrEmpty(typeValidator) ? string.Format(
                checkFileTypeFunction, this.AllowedFileTypes, 
                this.InvalidFileTypeErrorMessage) : string.Empty,
            this.MaxFileSize > 0 ? string.Format(this.sizeValidationFunction, 
                this.MaxFileSize, this.InvalidFileSizeErrorMessage) : string.Empty,
            this.OnSelectFunction,
            this.OnErrorFunction,
            this.OnCompleteFunction
        );
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, this.script, true);
    }
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        StringBuilder sb = new StringBuilder();
        string uploadImage = string.IsNullOrEmpty(this.UploadImage) ? string.Concat(this.RootUrl, 
            ResourceManager.GetResourcePath("FileUploadField.Upload.png"this.GetType(), this.Page)) : 
            this.ResolveUrl(this.UploadImage);
        string cancelAllImage = string.IsNullOrEmpty(this.CancelAllImage) ? string.Concat(this.RootUrl, 
            ResourceManager.GetResourcePath("FileUploadField.CancelAll.png"this.GetType(), this.Page)) : 
            this.ResolveUrl(this.CancelAllImage);
        sb.AppendFormat("<div class=\"{0}\">"this.GetType().Name);
        sb.AppendFormat(
            @"<input type=""file"" name=""{0}"" id=""{1}"" />"this.UniqueID, this.ClientID);
        sb.AppendFormat(
            @"<a class=""Button"" href=""javascript:javascript:$('#{0}').uploadifyUpload();"">
            <img src=""{1}"" alt=""Upload"" /></a>", 
            this.ClientID, uploadImage);
        sb.AppendFormat(
            @"<a class=""Button"" href=""javascript:jQuery('#{0}').uploadifyClearQueue()"">
            <img src=""{1}"" alt=""Cancell All"" /></a>"this.ClientID, cancelAllImage);
        sb.AppendFormat(@"<div id=""{0}""></div>", 
            this.QueueId.Equals("fileQueue") ? string.Concat(this.ClientID, this.QueueId) : this.QueueId);
        sb.Append("</div>");
        writer.Write(sb.ToString());
    }
 
    #endregion
}


File Hanlder
public class UploadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        bool overLimitFile = false;
        string[] values = context.Request.QueryString.Get(QueryParameters.Params).Split(";".ToCharArray());
        double maxSize = double.Parse(values[0]);
        string fileUploadFolder = values[1];
        double limit = maxSize * 1024 * 1024;
        try
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            string extension = Path.GetExtension(file.FileName);
            string strFile = string.Format("~/{0}/{1}{1}", fileUploadFolder, 
                Guid.NewGuid().ToString().Replace("}"string.Empty).Replace("{"string.Empty), extension);
            if (limit != 0 && file.InputStream.Length > limit)
            {
                overLimitFile = true;
                throw new Exception();
            }
            file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(strFile));
            context.Response.Write("1");
        }
        catch
        {
            if (overLimitFile) context.Response.Write("0");
            else context.Response.Write("-1");
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...