DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Dynamic File Upload Component in Salesforce LWC
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Trending

  • How to Format Articles for DZone
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • How Clojure Shapes Teams and Products
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit Using Container Images (Part 2)
  1. DZone
  2. Coding
  3. Frameworks
  4. Async file upload with jquery and ASP.NET

Async file upload with jquery and ASP.NET

By 
Jalpesh Vadgama user avatar
Jalpesh Vadgama
·
Dec. 24, 11 · News
Likes (0)
Comment
Save
Tweet
Share
66.6K Views

Join the DZone community and get the full member experience.

Join For Free
Recently before some I was in search of good asynchronous file upload control which can upload file without post back and I have don’t have to write much custom logic about this. So after searching it on internet I have found lots of options but some of the options were not working with ASP.NET and some of work options are not possible regarding context to my application just like AsyncFileUpload from Ajax toolkit.As in my application we were having old version of Ajax toolkit and if we change it than other controls stopped working. So after doing further search on internet I have found a great Juqery plugin which can easily be integrated with my application and I don’t have to write much coding to do same.

So I have download that plug from the following link. This plug in created by yvind Saltvik

http://www.phpletter.com/Our-Projects/AjaxFileUpload/

After downloading the plugin and going through it documentation I have found that I need to write a page or generic handler which can directly upload the file on the server. So I have decided to write a generic handler for that as generic handler is best suited with this kind of situation and we don’t have to bother about response generated by it.

So let’s create example and In this example I will show how we can create async file upload without writing so much code with the help of this plugin. So I have create project called JuqeryFileUpload and our need for this example to create a generic handler. So let’s create a generic handler. You can create a new generic handler via right project-> Add –>New item->Generic handler just like following.

GenericHandlerForJqueryFileUploadwithASPNET
I have created generic handler called AjaxFileuploader and following is simple code for that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace JuqeryFileUPload
{
   /// <summary>
   /// Summary description for AjaxFileUploader
   /// </summary>
   public class AjaxFileUploader : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           if (context.Request.Files.Count > 0)
           {
               string path = context.Server.MapPath("~/Temp");
               if (!Directory.Exists(path))
                   Directory.CreateDirectory(path);

               var file = context.Request.Files[0];

               string fileName;

               if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
               {
                   string[] files = file.FileName.Split(new char[] { '\\' });
                   fileName = files[files.Length - 1];
               }
               else
               {
                   fileName = file.FileName;
               }
               string strFileName=fileName ;
               fileName = Path.Combine(path, fileName);
               file.SaveAs(fileName);


               string msg = "{";
               msg += string.Format("error:'{0}',\n", string.Empty);
               msg += string.Format("msg:'{0}'\n", strFileName);
               msg += "}";
               context.Response.Write(msg); 


           }
       }

       public bool IsReusable
       {
           get
           {
               return true;
           }
       }
   }
}

As you can see in above code.I have written a simple code to upload a file from received from file upload plugin into the temp directory on the server and if this directory is not there on the server then it will also get created by the this generic handler.At the end of the of execution I am returning the simple response which is required by plugin itself. Here in message part I am passing the name of file uploaded and in error message you can pass error if anything occurred for the time being I have not used right now.

As like all jQuery plugin this plugin also does need jQuery file and there is another .js file given for plugin called ajaxfileupload.js. So I have created a test.aspx to test jQuery file and written following html for that .
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="JuqeryFileUPload.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
   <script type="text/javascript" src="jquery.js"></script>
   <script type="text/javascript" src="ajaxfileupload.js"></script>
</head>
<body>
   <form id="form1" runat="server">
   <div>
         <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
         <button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
         <img id="loading" src="loading.gif" style="display:none;">
   </div>
   </form>
</body>
</html>


As you can see in above code there its very simple. I have included the jQuery and ajafileupload.js given by the file upload give and there are three elements that I have used one if plain file input control you can also use the asp.net file upload control and but here I don’t need it so I have user file upload control. There is button there called which is calling a JavaScript function called “ajaxFileUpload” and here we will write a code upload that. There is an image called loading which just an animated gif which will display during the async call of generic handler. Following is code ajaxFileUpload function.
<script type="text/javascript">
   function ajaxFileUpload() {
       $("#loading")
   .ajaxStart(function () {
       $(this).show();
   })
   .ajaxComplete(function () {
       $(this).hide();
   });

   $.ajaxFileUpload
   (
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fileToUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert(data.msg);
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )

       return false;

   }
</script>

As you can see in above code I have putted our generic handler url which will upload the file on server as url parameter. There is also parameter called secureURI is required to be true if you are uploading file through the secure channel and as a third parameter we have to pass a file upload control id which I have already passed and in fourth parameter we have to passed busy indicator which I have also passed. Once we passed all the parameter then it will call a method for plugin and will return response in terms of message and error. So There is two handler function written for that.

That’s it. Our async file upload is ready. As you can easily integrate it and also it working fine in all the browser. Hope you like it. Stay tuned for more. Till then happy programming..
Upload ASP.NET JQuery

Published at DZone with permission of Jalpesh Vadgama, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Dynamic File Upload Component in Salesforce LWC
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!