Uploading Files Using HTML5 Drag-and-Drop and ASP.NET

Introduction

ASP.NET web applications that require uploading files from the client machine to the server use the file field to select files. The selected files are uploaded to the server using form submission techniques. In addition to the file field, HTML5 also allows you to select files using drag and drop. Using this feature you can drag files from Windows Explorer or Desktop and drop them on a predefined area of a web page. The files can then be uploaded to the server. This article illustrates how the HTML5 drag and drop feature can be used to upload files on the server.  

Selecting Local Files using HTML5 Drag and Drop

Traditionally you use the HTML file field to select files that are to be uploaded to the server. ASP.NET web forms wrap the file field into the FileUpload server control and ASP.NET MVC applications can use an <input> element with type attribute set to file. Another alternative offered by HTML5 is dragging one or more files from Windows Explorer or Desktop and drop them onto some predefined HTML element of a web page. You can then access the dropped files using the dataTransfer object available to drag and drop events. Discussing HTML5 drag and drop from the ground up is beyond the scope of this article. If you are unfamiliar with HTML5 drag and drop read this article first.

To understand how files can be selected using the drag and drop features of HTML5, let's develop a new ASP.NET web forms application. The HTML markup of the default web form is shown below:

<form id="form1" runat="server">
<center>
  <div id="box">Drag & Drop files from your machine on this box.</div>
  <br />
  <input id="upload" type="button" value="Upload Selected Files" />
</center>
</form>

As you can see, the <form> consists of a <div> element and a button. The <div> element is intended to drop the files dragged from the local machine. Merely dropping the files won't upload them to the server. Clicking on the button initiates the file upload operation.

To handle the file drop operation you need to wire certain event handlers to the box <div> element. The following jQuery code shows how that can be done:

var selectedFiles;

$(document).ready(function () {
  var box;
  box = document.getElementById("box");
  box.addEventListener("dragenter", OnDragEnter, false);
  box.addEventListener("dragover", OnDragOver, false);
  box.addEventListener("drop", OnDrop, false);
...
}

The code declares a global variable named selectedFiles for storing a list of selected files. The ready() function wires three event handler functions to the respective events of the box <div> element, viz. dragenter, dragover and drop using addEventListener() method. The first parameter of the addEventListener() method is the event name and the second parameter is the event handler function. The event handler functions are shown below:

function OnDragEnter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function OnDragOver(e) {
  e.stopPropagation();
  e.preventDefault();
}

function OnDrop(e) {
  e.stopPropagation();
  e.preventDefault();
  selectedFiles = e.dataTransfer.files;
  $("#box").text(selectedFiles.length + " file(s) selected for uploading!");
}

The OnDragEnter() and OnDragOver() event handler functions are simple and they merely prevent the event bubbling of the respective events. The OnDrop() function is important since it handles the drop event. The list of files dragged and dropped on the <div> element is obtained using the files property of the dataTransfer object. The files object is of type FileList and each item of the FileList collection is of type File. These two objects are available as a part of the HTML5 File API. The OnDrop() function stores the selected files in the global variable - selectedFiles and displays a message in the <div> using the text() method that indicates the number of files selected. The following figure shows how the default web form looks after dragging and dropping files on the <div> element.

Default web form after dragging and dropping files to the <div> element
 

Default web form after dragging and dropping files to the <div> element

Sending Files to the Server Using jQuery

To send the selected files from the client to the server you can use different techniques but in this example you will use jQuery $.ajax() method for uploading the files. The following code shows how $.ajax() method can be used for this purpose.

$("#upload").click(function () {
  var data = new FormData();
  for (var i = 0; i < selectedFiles.length; i++) {
    data.append(selectedFiles[i].name, selectedFiles[i]);
  }
  $.ajax({
    type: "POST",
    url: "FileHandler.ashx",
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
      alert(result);
    },
    error: function () {
      alert("There was error uploading files!");
    }
  });
});

The code shown above first creates a FormData object. The FormData object encapsulates form's data that you wish to send to the server. All the selected files are added to the FormData object using its append() method. The first parameter of the append() method is the name of the file being added and the second parameter is the File object itself. Once the FormData object is ready you make a POST request to a Generic ASP.NET Handler (FileHandler.ashx) using jQuery $.ajax() method. You will create the generic handler in the next section.

The type of the request is POST. The url is FileHandler.ashx. Notice that the processData option is set to false. By default when you use the $.ajax() method the data is sent in URL encoded format. To prevent this behavior processData is set to false. The data option  is set to the FormData object created earlier. The success function simply displays the message returned by the generic handler. The error handler function displays an error message in case there is any error while calling FileHandler.ashx.

Receiving the Uploaded Files on the Server

The ASP.NET generic handler - FileHandler.ashx - receives the files sent by the $.ajax() method. The generic handler also saves them to a folder on the server. The following code shows how the handler accomplishes this task:

public void ProcessRequest(HttpContext context)
{
    if (context.Request.Files.Count > 0)
    {
        HttpFileCollection files = context.Request.Files;
        foreach (string key in files)
        {
            HttpPostedFile file = files[key];
            string fileName = file.FileName;
            fileName = context.Server.MapPath("~/uploads/" + fileName);
            file.SaveAs(fileName);
        }
    }
    context.Response.ContentType = "text/plain";
    context.Response.Write("File(s) uploaded successfully!");
}

The ProcessRequest() method of the FileHandler.ashx is called when the files are sent to the server using the $.ajax() method. The uploaded files can be accessed using the Files collection of the Request object. Each item inside the Files collection is of type HttpPostedFile. A foreach loop iterates through all the files from the Files collection and saves the individual file using the SaveAs() method of HttpPostedFile class. Once all files are saved a success message is sent to the client.

Note that by default ASP.NET sets request length to 4096 bytes. If you wish to upload large files you may adjust the request length using web.config file as shown below:

 <httpRuntime 
   maxRequestLength="20000"
   requestValidationMode="4.5" 
   targetFramework="4.5" 
   encoderType="..." />

As you can see the maxRequestLength attribute of the <httpRuntime> section is set to 20000 bytes. You need to adjust this value as per your requirement.

That's it! You can now run the web form, drag and drop files on the <div> element and click on the "Upload Selected Files" button to upload them on the server. 

Summary

Traditionally HTML allowed you to select files for uploading using file fileds. HTML5 allows you to drag files from Windows Explorer or Desktop and drop them onto an element of a web page. The drop event handler can access the selected files using the files property of the dataTransfer object. The files can then be uploaded onto the server using $.ajax() method. The drag and drop file upload is easy and convenient, especially when multiple files are to be uploaded.

 



Related Articles

Downloads

Comments

  • How to submit the same Form without jQuery

    Posted by Bilal Haidar on 09/12/2014 06:20am

    Hi, Assume, we don't wanna submit the files with jQuery. How would we do it using ASP.NET full page submit? Thanks

    Reply
  • reviews after euphemistic pre-owned my clarisonic pro

    Posted by iouwanzi on 06/06/2013 08:37pm

    [url=http://www.australiaclarisonic.com/]cheap clarisonic australia[/url] Vous venez ou peut-être pas ?Le brushing appartenant au régime a été effectuée ainsi que les nouveaux frais AIR compétents sèche-cheveux dans GHD.Katy Perry que n’est plus une sirène, mais il semble être partout destiné à nouveau modèle « ghd lisseur ».Pour promouvoir l’idée de tresses tendres et même brillant cette fois tout le produit inclut consacrée à une série de photographies sur les Afro-américains et lumineuse. Un plan qui est beaucoup plus maîtrisable par rapport aux dernières belles activités. Une exploitation avec un tresses spécialement volumineux sur les portraits. [url=http://www.miaclarisonicaustralia.org/clarisonic-classic]clarisonic classic[/url] Victoria Secret 2012, la dernière conférence de maillots de bain sur la belle Miranda Kerr trésor et sexy top model Candice Swanepoel lors de la sélection se tailler un style de grands ghd lisseur cheveux de milliers de féminité sexy. Mannequin ange sexy pour Victoria Secret 2012, la dernière Maillots de bain pour la publicité, [url=http://www.australiaclarisonic.com/clarisonic-mia]clarisonic mia[/url] Mon conjoint et moi posséder prolongée (pratique pour vous aider mes coudes personnels) mince, okay, colorés mais aussi soulignée, nui chevelure. Votre ghd Midnight styler ne blessure notre chevelure (d’autres plutôt que j’exécute sans doute!)#) en quelque sorte. Mon conjoint et moi faire utiliser ses programmes pour créer plus Eufora lavage et aussi revitalisant. Mon conjoint et je crois que les éléments que vous employez, qui incluent le shampooing et revitalisant, un impact véritablement un nouveau) la méthode que vous vos cheveux ressemble et se sent tout de suite après devenir formé avec b) Comment un fer plat fonctionne et se comporte de même à votre chevelure.

    Reply
  • comamoodimi LaXanapseBave voicioxobby 11128

    Posted by Katterarf on 06/03/2013 03:22am

    groutbarrit Keep your vision clear and your cheap jerseyslook bold with the Oakley Batwolf Sunglasses. groutbarrit This unique oakley Batwolf sunglass has acheap mlb jerseysThree-Point Fit that keeps the groutbarrit Keep your vision clear and your cheap jerseyslook bold with the Oakley Batwolf Sunglasses. groutbarrit The three-point fit keepswholesale nhl jerseysthe optics in precise alignment while dual cam hinges blend smoothly into the sculpture. _________________________________________________________________________________________________________

    Reply
  • トリーバーチ 店舗 VHsnm91Tz

    Posted by Twereerejuddy on 05/30/2013 08:44am

    2013春夏新作トリーバーチ大好評販売中 !絶対にお 買得! groutbarrit ティファニー 最適なトリーバーチ 財布商品が必ず見つかる!クリスメスプレゼント特集。 groutbarrit ティファニー ネックレス

    Reply
  • The ideal key for sneakers for you to discover more about as we speak.

    Posted by BobHotgloff on 05/22/2013 12:11pm

    The Solutions To Learn about shoes And Also How One Might Join The shoes Elite [url=http://www.shoesja.biz/]アシックス[/url] Units and performance throughout Vegas : sneakers simply leaves with no goodbye [url=http://www.shoesja.biz/adidas-アディダス-c-64.html]adidas[/url] The most important sneakers Corporate Speak : Persons who cares about zero benefits?! [url=http://www.shoesja.biz/new-balance-ニューバランス-c-21.html]newbalance[/url] Brand new questions on shoes replied not to mention why you should definitely analyze every single message of this specific insider report. [url=http://www.shoesja.biz/nike-ナイキ-c-44.html]ナイキ ランニングシューズ[/url] The best ways to find out nearly anything there is to know surrounding sneakers in Few relatively easy steps. [url=http://www.kutuja.com/]靴 通販[/url] The correct way to learn anything and everything there is to know concerning shoes in four easy steps. [url=http://www.kutuja.com/adidas【アディダス】-c-1.html]アディダス[/url] Most recent questions about sneakers replied and therefore reasons why you has got to read through each and every word in this expose. [url=http://www.kutuja.com/new-balance【ニューバランス】-c-206.html]ニューバランス キッズ[/url] The very best strategy for shoes that one can find out more about straight away. [url=http://www.kutuja.com/nike【ナイキ】-c-215.html]nike[/url] A double strain on shoes [url=http://www.shoesjp.biz/]アディダス[/url] The Trick For shoes [url=http://www.shoesjp.biz/adidas【アディダス】-c-640.html]adidas アディダス[/url] Yet another double take on shoes

    Reply
  • n0udvau cigar

    Posted by grwastqz on 05/20/2013 04:41pm

    kti0xsth my9nvko3 f54yewr4t536 ywd8dvzi w7osl7wf

    Reply
  • cheap authentic ncaa jerseys from china,thailand mexico jersey

    Posted by AffongeAtorge on 05/07/2013 11:21am

    Barcelona micro-blog is still struggle to solve their very own difficulties within defence. If the Spanish training Barcelona this specific months just what spot, that is certainly compared to earlier periods, considerably breakable defence. "Daily athletics newspaper" explained, good defence must become Barca's burden, not would like to lock that League not essential choices, with all the hearth used, Barcelona need to be careful. Nonetheless, in order to reinforce that safety collection, once activation, Barcelona high-rise also executed that motion, reported by that "daily athletics newspaper" documented, Barcelona own arrived at an agreement by using Dortmund, [url=http://shopnfljerseys.bravesites.com]cheap soccer jerseys[/url] that reddish colored in addition to orange affiliate internet marketing is most likely the price of 25000000 euros to propose Hummel J Vilanova right now, nonetheless absolutely no decision continues to be produced, due to the fact he or she is a lot more for instance Tiago Silva. With regard to Barcelona only intent to make minimal vehicle repairs as well as considerable reform difficulties, that supporters have got a incredibly hot discussion, nonetheless there is no-one to deny which, following on from the safety Barcelona high-rise will be the very first choice of building up that crew. Barcelona private coach collection won't consider baltra, Cameroon songs offers established not ideal for trying to play within Zhongwei, and also the chance for Eric Abidal up coming months giving Barcelona are also good. Website, Barcelona up coming months only Peake, Puyol these kinds of not one but two reliable Zhongwei, in addition to Puyol personal injury, trying to play moment is not assured. The creation of Hummel J happens to be any pushing make any difference in the instant to Barcelona, in addition to Hummel J themselves in the particular approach, phrase in the Barcelona yearning. Hummel J uploaded any kissing any girl's photos about his / her tweets bill, even so the most fascinating is actually, guiding the 2 main men and women, any Barca tank top since background business presentation. It really is challenging to put any Barca tank top since proof regarding Hummel J to work with Nokamp, nevertheless , you desire, this specific snapshot is often a transmission with regard to Hummel J to present. Hummel J is actually Prosecute pizza thunder podium picked players for instance Tiago Silva, Villanova, nonetheless judging in the present circumstance, is actually a lot more challenging compared to dig dug Tiago Hummel J from Dortmund, Silva from Paris St germain. [url=http://shopnfljerseys.bravesites.com]cheap soccer jerseys[/url] Vilanova needs to be practical. This nights I used to be in the Standford fills, watching Chelsea beat Basel, in to the Europa League play-off activity, well then , i'll essentially the most remarkable will be the central in the crew, an awesome nonetheless as, despite the fact that from Chelsea's criteria, its efficiency this specific months can be good and the bad. Because of this view, you should congratulate that interim private coach Benitez, due to the fact this individual was in any challenging atmosphere, carrying out a good career. Nonetheless once you sit in the stands, since Post watched that Chelsea players, you can pull any conclude, that is the team's line-up is not essential, an excess of at this time, the existing workforce continues to be good. Nonetheless I believe which, in order to make it possible for that Chelsea squad a lot more healthy, they will nonetheless want man or women supplementation. Mourinho initially can be in search of any striker, his / her outdated Chelsea is actually designed around Drogba, might be predicted, he can repeat.

    Reply
  • qdcgvrse 622398

    Posted by sshzhszuc on 05/07/2013 12:47am

    michael kors christian louboutin outlet tiffany and co outlet Theseprocesses has allowed for a high volume of imitation turquoise jewellery products to enter the market, and for these products to be sold at a considerably lower prices than designs that have been handcrafted from the genuine stone http://www.ghdzone.co.uk/

    Reply
  • ebmiuziq 893356

    Posted by ndccjlsle on 04/29/2013 09:05pm

    christian louboutin outlet uk cheap christian louboutin burberry handbags People, who would actually say that parenting is a straightforward career, are the types who most very likely are childless http://www.windowswest.com/.au/data/chaneloutlet.html

    Reply
  • What everyone else does in the area of nike and consequently exactly what you need to perform completely different.

    Posted by icoppyapedcap on 04/21/2013 10:26pm

    Uq [url=http://hunter-rain-boots.webnode.jp]ハンターブーツ[/url] eDh [url=http://hunterrainbootsjp.webnode.jp]ハンターレインブーツ[/url] o ChnCrb HpvF [url=http://hunter-boots8.webnode.jp]レインブーツメンズ[/url] cf M [url=http://rain-boots-men.webnode.jp]長靴[/url] wm [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツ人気[/url] ZckDtkMwc U[url=http://rainshoesja.webnode.jp]ブーツ[/url] ztHahGfpEa [url=http://ja-hunter-rain-boots.webnode.jp]ハンターレインブーツ[/url] p HznIxa [url=http://rain-boots-popular.webnode.jp]レインブーツメンズ[/url] Myp [url=http://rain-boots-men6.webnode.jp]レインブーツハンター[/url] Sfo Mxz [url=http://jahunterrainboots.webnode.jp]レインブーツメンズ[/url] Xqv

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds