SIGN UP MEMBER LOGIN:    
ARTICLE

AJAX File Upload using JQuery

Posted by Sateesh Arveti Articles | JQuery April 01, 2010
In this article, we will look into file upload using JQuery plug-in. Ajax file upload plug-in allows us to upload files to server.
Reader Level:
Download Files:
 

In this article, we will look into file upload using JQuery plug-in. Ajax file upload plug-in  allows us to upload files to server. I am going to explain it with an example. We will be using custom HTTP handler to upload file onto the server. Create an ASP.NET MVC web application and name it as JQueryFileUpload. Now, add below scripts to site.master:

<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>

Now, goto Index view under Home controller and add below html:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div id="uploadStatus" style="color: red;"></div>
    <input type="button" id="uploadFile" value="Upload File" />
    <div id="fileList"></div>
</asp:Content>

We are using uploadStatus tag to show status message while uploading/deleting a file. uploadFile button is used to select the file to be uploaded. fileList tag is used to show list of files uploaded. Add a new class to the solution and name it as FileUploadHandler. This class will act as custom HTTP handler for uploading/deleting file. Add below code to the class:

public class FileUploadHandler: IHttpHandler
{
    #region IHttpHandler Members
    public bool IsReusable
    {
        get { return false; }
    }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            //Uploaded File Deletion
            if (context.Request.QueryString.Count > 0)
            {
                string filePath = @"c:\DownloadedFiles\" + context.Request.QueryString[0].ToString();
                if(File.Exists(filePath))
                File.Delete(filePath);
            }
            //File Upload
            else
            {
                string fileName = Path.GetFileName(context.Request.Files[0].FileName);
                string location = @"c:\DownloadedFiles\" + fileName;
                context.Request.Files[0].SaveAs(location);
            }
        }
        catch
        {
        }
    }
    #endregion
}

We  implemented IHttpHandler and defined code to upload/delete file  in ProcessRequest(). We are deleting a uploaded file by passing its name as parameter. We need to register the HTTP handler by adding below tag to web.config in httpHandlers section for any .upload request. 

<add path="*.upload" verb="*" type="JQueryFileUpload.FileUploadHandler"/>

Now, add below script to site.master for making ajax call for upload/delete of the file.

<script type="text/javascript">
    $(function() {
        //Function to upload file.
        new AjaxUpload('#uploadFile', {
            action: 'FileUploadHandler.upload',
            name: 'upload',
            onComplete: function(file) {
                $('<div><img src="../../Content/delete.jpg" style="width:20px;height:20px" class="delete"/>' + file + '</div>').appendTo('#fileList');
                $('#uploadStatus').html("Upload Done.");
            },
            onSubmit: function(file, ext) {
                if (!(ext && /^(txt|doc|docx|xls|pdf)$/i.test(ext))) {
                    alert('Invalid File Format.');
                    return false;
                }
                $('#uploadStatus').html("Uploading...");
            }
        });
        //Function to delete uploaded file in server.
        $('img').live("click", function() { $('#uploadStatus').html("Deleting"); ; deleteFile($(this)); });
    });
    function deleteFile(objfile) {
        $.ajax({ url: 'FileUploadHandler.upload?del=' + objfile.parent().text(), success: function() { objfile.parent().hide(); } });
        $('#uploadStatus').html("Deleted");
    }
</script>

We are using AjaxUpload function to upload file. We specified action as our HTTP handler and used onComplete and onSubmit events to show status of file upload. We are specifying file formats accepted for uploading in onSubmit event by its file extension. Finally, add below line to Global.asax under RegisterRoutes to skip routing for our HTTP handler:

routes.IgnoreRoute("{file}.upload");

Run the application, use Upload File button for selecting and uploading the file. Click on delete icon to delete corresponding file in the server.

I am ending the things here. I am attaching the source code with it. I hope this article will be helpful for all.

Login to add your contents and source code to this article
share this article :
post comment
 

I want Javascript with Html File only.

Posted by BASKER RAJAVEL Mar 14, 2012

Poor code

Posted by Roy Tynan Feb 11, 2011

when i run it on a proper server (iis) it fails to save the file or see any bytes in the context.Request.InputStream (which was to be a way of holding the file before the user saved it at which point it would be saved to the database). am i having this problem because I don't have an MVC app (and haven't been able to add the routes code to my Global.asax file? Thanks again and I'm hoping this can be made to work as it's great.

Posted by Richard Northcott Jan 20, 2011

Hi Author,

Could you please let me know how can I get the file size of the respective file which we are uploading using your code.

Thanks,
Vivek

Posted by Vivek Kandagatla Oct 05, 2010

I noticed that visual studio includes a reference to system.web.mvc 1.
I had to remove it and added system.web.mvc 2 reference to the project.
Now I was able to run it in visual studio (2008)

Posted by Roger Keizer Aug 10, 2010
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor