The Wayback Machine - https://web.archive.org/web/20130703052959/http://www.codeguru.com:80/csharp/csharp/cs_internet/uploading-files-using-html5-drag-and-drop-and-asp.net.htm

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

IT Offers

Comments

  • 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
  • The thing other people engages in relating to nike and moreover precisely what you would want to complete different.

    Posted by icoppyapedcap on 04/21/2013 10:59am

    Er [url=http://hunter-rain-boots.webnode.jp]ハンターブーツ[/url] kCx [url=http://hunterrainbootsjp.webnode.jp]ハンターブーツ[/url] a CskLce JciJ [url=http://hunter-boots8.webnode.jp]レインブーツハンター[/url] wl E [url=http://rain-boots-men.webnode.jp]ブーツ[/url] ep [url=http://hunter-rain-boots-ja.webnode.jp]レインブーツ[/url] BanJjfSwv U[url=http://rainshoesja.webnode.jp]ブーツ[/url] elEubLcbSc [url=http://ja-hunter-rain-boots.webnode.jp]ハンター長靴[/url] e YzsHac [url=http://rain-boots-popular.webnode.jp]レインシューズ[/url] Phz [url=http://rain-boots-men6.webnode.jp]レインブーツハンター[/url] Nqz Tju [url=http://jahunterrainboots.webnode.jp]ハンターブーツ[/url] Rjj

    Reply
  • Jordan shoes mentioned Gene to buy the manufacturer, a division of Nike

    Posted by TaddyGaffic on 04/20/2013 06:06am

    Where did that get us? A bunch of banks writing loans that they didnt care if poeple would be able to pay for because they were conforming [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] loans and Fannie and Freddie would back them. And their $150+ billion losses show that they are just as unable to predict or control the market as the rest of us. It won't work because it doesn't reward investors for taking the risks involved. In order to set a good example of following your dreams, you may wish to consider strictly limiting, or eliminating TV from your life. When people are involved in pursuing their dreams they often find that they do not have the time to watch TV. TV just gets in the way of pursuing other dreams.. Take a limousine ride with Aerosmith on one of the fastest rollercoaster you have to face. Live shows throughout the day from Beauty and the Beast [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] will bring memories flooding back for young and old. You can get closer to the action and feel that he wanted to be in the spotlight. Other technology advancements are the midsole. It has a compression molded EVA for lasting impact protection. A Vibrakill shock-absorber in the heel provides a lot of [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] comfort, and the Exact Pro technology combines a pebax plate and a Dynamic camflex in the forefoot for improved energy return on every step. Meindl Borneo Lady Pro - This shoe is just one of my wifes most popular hiking boots. It is appropriate for lengthy outdoor hikes and you can actually do a tiny stretch of hill hiking whilst sporting them. This product also includes memory foam

    Reply
  • pbaarure 906684

    Posted by jkqwliglw on 04/14/2013 11:56pm

    Hermes Handbags Gucci Outlet Online Louboutin Pumps Sounds simple, doesn't it?The trick to healthy living is making small changes http://outlethermesonline.tripod.com/

    Reply
  • rwlxayea 546402

    Posted by zdcbbcwdc on 04/14/2013 10:54pm

    Hermes Handbags for sale cheap christian louboutin shoes hermes online Again, do not just make assumptions that certain brands are best; take advantage of bread machine reviews so you can check the reliability of the brand and model http://handbagsoutletonline.tripod.com

    Reply

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds