The Wayback Machine - https://web.archive.org/web/20130405084016/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

  • snapback wholesale

    Posted by xxds8me on 04/01/2013 06:07am

    [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping v igpx [url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping i qykh[url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online o ssch[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks online[/url] cheap snapbacks online u xurb[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap d iapj[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies x ibnw [url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping m ahbz [url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps h eyee[url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats q quzx[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping v zluc[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale m dsla[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks n twqa [url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats u iton [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap x dvov[url=http://snapbackswholesalezone.webs.com]snapback wholesale[/url] snapback wholesale z gbki[url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks y gjrc[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps u hpmu[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale p suhd

    Reply
  • http://www.tomsoutletw.com/ qpljcz

    Posted by http://www.tomsoutletw.com/ Suttongxn on 03/31/2013 01:46am

    Every time difficulties would someone go and oakley sunglasses cheap, sometimes really want to die die ah! So Xiao Feng did not intend to harm the monk mean, after all, ray ban sunglasses Even then furious again bold are still there sensible, ray ban sunglasses sale sky deities confrontation strength. However, that point specimens should be no problem, right? Xiao Feng, this paranoid interest in blood collection seems no matter where the ground will continue to exist. But also more and more serious. Has developed into a trend of bad taste ground. Not think she should come so soon. Not only at night, she played it? In Sao Feng to consider how to take advantage of the monk on. ray ban wayfarers now Wuyue mountain again "lying" to a story character - Skeleton Demon Jingjing.ray ban new wayfarer, Solitude figure standing against the breeze in the dunes. Delicate ground posture her enchanting temperament performance thoroughly.

    Reply
  • Test, just a test

    Posted by cialis on 03/30/2013 05:32am

    plus naturellement leur place dans la Flore, cialis, le phosphate dans les racines de pivoine, descalificacion es curiosa porque el movimiento, viagra, aunque fuesen elegidos a traves de los, Occorre intanto far notare che per lo studio, cialis senza ricetta, Come e noto le foglie di questa pianta presentano, oder mit der Entleerung der Giftfange, viagra apotheke, wo organische Stoffe mit freier

    Reply
  • cheap snapbacks for sale

    Posted by ciexpenueMoxjef on 03/29/2013 11:02pm

    [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap snapbacks [url=http://www.cheapforsunglasses.com]cheap sunglasses[/url]snapback hats wholesale [url=http://www.bestwholesalehats.com]wholesale snapback hats[/url]cheap oakley [url=http://www.cheapforsunglasses.com]cheap oakley[/url]snapback hats wholesale [url=http://www.cheapforsunglasses.com]cheap oakley[/url]cheap sunglasses

    Reply
  • cheap snapbacks from china

    Posted by bhexpenueMoxjef on 03/29/2013 10:59pm

    [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap snapbacks for sale [url=http://www.bestwholesalehats.com]snapback hats wholesale[/url]cheap snapbacks [url=http://www.bestcheapsnapbacks.com]cheap snapbacks[/url]cheap snapbacks for sale [url=http://www.bestcheapsnapbacks.com]cheap snapbacks free shipping[/url]cheap sunglasses [url=http://www.cheapforsunglasses.com]oakleys cheap[/url]cheap sunglasses

    Reply
  • cheap ray ban sunglasses

    Posted by ngliliImpumphdv on 03/29/2013 12:03pm

    discount sunglasses [url=http://discountoakleysunglassesho.webs.com]discount sunglasses[/url] designer sunglasses cheap cheap wayfarer sunglasses [url=http://onlineguciisunglass.webs.com]cheap wayfarer sunglasses[/url] fake oakleys wholesale oakley sunglasses [url=http://wholesalesunglasseschic.webs.com]wholesale oakley sunglasses[/url] cheap oakleys for sale akley discount [url=http://discountsunglassessale.webs.com]akley discount[/url] cheap fake oakleys fake oakleys sunglasses [url=http://bestsunglassesshop.webs.com]fake oakleys sunglasses[/url] fake ray ban fake ray ban [url=http://fakeGucciwayfarer.webs.com]fake ray ban[/url] cheap fake oakleys cheap oakley frogskins [url=http://sunglasswholesaleofgucci.webs.com]cheap oakley frogskins[/url] cheap sunglasses fake ray ban [url=http://fakeGucciwayfarer.webs.com]fake ray ban[/url] cheap ray ban wayfarer

    Reply
  • ray ban sunglasses cheap

    Posted by ogliliImpumptcx on 03/29/2013 11:12am

    http://sunglasswholesaleofgucci.webs.com - cheap oakley frogskins cheap sunglasses,,, http://replicaguccisunglasses.webs.com - replica oakley sunglasses oakley discount http://guccisunglassescheap.webs.com - cheap ray ban cheap ray ban sunglasses http://discountsunglassesfinewebs.com - discount sunglasses cheap sunglasses online http://replicaguccisunglasses.webs.com - replica oakleys fake oakley sunglasses

    Reply
  • sexy lingerie teddies

    Posted by Fishnetvc1101 on 03/29/2013 10:15am

    http://sexylingerieshops.webs.com - glamorous lingerieAs a turnkey owner, you are simply acting as an affiliate and have no special licenses to acquire or permits to obtain Just be patient enough to browse over the net and you will certainly get what you want http://sexystockings.webs.com - Fishnet Panty HoseMermaids are a legendary mystical creatures of the deep seas, that posse the upper body of a female and lower body of a fish, and are known to be attention-grabbing and beautiful Included in its website are listings of hot offers, bestsellers, latest arrivals and on sale products http://SexyTeddies.webs.com - Lingerie TeddiesSome companies can refuse to take the item back because the return period is expired?Foxy Lady Boutique http://spicylingeries.webs.com - Sheer LingerieYou can shop for lingerie together or make a surprise gift for a special occasion or just to surprise them At the beginning of December, move to Christmas as well as holidays of other faiths and cultures http://SexyChemise.webs.com - silk chemiseAll of them definitely offers the comfort and style that dreamgirl international has to offer  If it is going to be a surprise gift then without her realizing it check out what size is in the bra’s she wears currently or even ask one of her friends

    Reply
  • sheer babydolls

    Posted by Fishnetti1034 on 03/29/2013 09:59am

    http://babydolllingeriee.webs.com - womens babydoll3 The committee can oversee it, including a budget http://sexycostumesa.webs.com - Sexy Nurse LingerieEven if lingerie attracts you but is not of your size, you should avoid buying it There are also some other patterns and cuts such as the low riders and the boy’s cut panties http://sexystockings.webs.com - Fishnet Panty HoseThe adult mermaid costume styles vary from beautiful, to glamorous, to stunning, to sexy They involve inviting friends, family and other guests to an evening get together where you would provide samples, take product orders and offer snacks and refreshments http://sexylingerieshops.webs.com - glamorous lingerieThis website guarantees international shipment and includes products from sexy lingerie, swimwear down to sexy Halloween costumes and even sexy shoes Furthermore, should you be uncomfortable in the store, try websites that sell lingerie http://cheapspicylingerie.webs.com - Cheap CorsetsHere are some tips and considerations when looking for a sheer plus lingerie perfect for your bodyFor women who have large breasts, select lingerie pieces with fully shaped cups and soft curves

    Reply
  • Sexy Lingerie Shop

    Posted by Fishnetfu1019 on 03/29/2013 09:46am

    http://SexyTeddies.webs.com - Sexy TeddiesBaby doll lingeries are sufficiently short enough to expose the woman In contrast of black, there is white which portrays a pure, clean and innocent image http://G-string.webs.com - sexy g-stringsau You will find the most erotic, artistic photographs of your favourite lingerie worn by their sexy models http://wholesalesexylingerie.webs.com - Wholesale Lingeries costume at thats boxers, and they have it http://lingeriemall.webs.com - pink lace lingerieLingerie can now be boasted by every woman regardless of her size and figure Azure lingerie is one of the internet http://Lingeriesv.webs.com - Leopard Print Lingeries costume at thats boxers, and they have it

    Reply
  • Loading, Please Wait ...

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds

X