Wednesday, August 21, 2013

ASP.Net: drag and drop file uploads using HTML5 DND and File API.


Client-Side Script and UI

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="upload.Upload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style>
body { padding:10px; font:14px/18px Calibri }
.bold { font-weight:bold }
td { padding:5px; border:1px solid #999 }
p, output { margin:10px 0 0 0 }
#drop_zone 

   margin:10px 0;
   width:40%; 
   min-height:150px; 
   text-align:center;
   text-transform:uppercase;
   font-weight:bold;
   border:8px dashed #898;
                height: 160px;
            }
</style>
    <title></title>
    <script>
        var files;
        function handleDragOver(event) {
            event.stopPropagation();
            event.preventDefault();
            var dropZone = document.getElementById('drop_zone');
            dropZone.innerHTML = "Drop now";
        }

        function handleDnDFileSelect(event) {
            event.stopPropagation();
            event.preventDefault();

            /* Read the list of all the selected files. */
             files = event.dataTransfer.files;

            /* Consolidate the output element. */
             var form = document.getElementById('form1');
             var data = new FormData(form);
           
             for (var i = 0; i < files.length; i++) {
                 data.append(files[i].name, files[i]);
             }
             var xhr = new XMLHttpRequest();
             xhr.onreadystatechange = function () {
                 if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
                     alert("upload done!");
                 } else {
                     //alert("upload failed!");
                 }
             };
             xhr.open('POST', "Upload.aspx");
            // xhr.setRequestHeader("Content-type", "multipart/form-data");
             xhr.send(data);
            
        }
</script>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
        
        <br />
        <div id="drop_zone">Drop files here</div>
</form>
</body>
    <script>
        if (window.File && window.FileList && window.FileReader) {
            /************************************ 
             * All the File APIs are supported. * 
             * Entire code goes here.           *
             ************************************/


            /* Setup the Drag-n-Drop listeners. */
            var dropZone = document.getElementById('drop_zone');
            dropZone.addEventListener('dragover', handleDragOver, false);
            dropZone.addEventListener('drop', handleDnDFileSelect, false);
            
        }
        else {
            alert('Sorry! this browser does not support HTML5 File APIs.');
        }
</script>
</html>

Server-side (Upload.aspx.cs)

using System;
using System.IO;
using System.Web;

namespace upload
{
    public partial class Upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
         if (IsPostBack)
         {
             UploadFile(sender,e);
         }
        }
        protected void UploadFile(object sender, EventArgs e)
        {
            HttpFileCollection fileCollection = Request.Files;
            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile upload = fileCollection[i];
                string filename ="c:\\Test\\" +  Path.GetRandomFileName();
                upload.SaveAs(filename);
            }
        }
    }

}

Thanks,
Din.

12 comments:

  1. What browsers will this work on?

    ReplyDelete
    Replies
    1. Let me know if it works for u...refer below comment for what browsers my code works

      Delete
  2. tested on IE 10,Chrome,Firefox,Safari 6.....doesn't work on safari for windows. mostly will works all the browsers which supports HTML 5 File API and HTML 5 "Drag and Drop".

    ReplyDelete
  3. What is the Limit of Uploaded File size?

    ReplyDelete
    Replies
    1. You can always change max file size, but the default i suppose is 4 MB.
      You can in web.config




      Delete
  4. I tried your example with small change:
    Drag&Drop in Upload.aspx page. After the file was dropped I open new window which send the data with xhr to the server- ashx (IHttpHandler).
    The problem is only in IE when Request.Files is empty on server.
    Do you have any idea what can be the problem?
    Thanks

    ReplyDelete
  5. Is there any way I could get the absolute path of the uploaded file? Thanks.

    ReplyDelete
  6. HI, thanks for the code, its working for other files but .msg files (outllok file). when I drag and drop msg file from outlook. It does't work. any help is appreciated!
    thanks

    ReplyDelete
    Replies
    1. .msg is not allowed IIS by default, check IIS MIME types. Add new MIME type and do IIS reset. It should work now.

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Titanium Works | TITIAN ART IN SPICIY - Titanium
    TITIAN omega titanium ART IN babyliss pro nano titanium SPICIY. titanium carabiners IN SPICIY. The titanium white octane blueprint art of stone and steel was used in all our paintings, with the aim of enhancing titanium wedding ring

    ReplyDelete