Wednesday, 21 August 2013

File upload using HTML5's drag and drop in Asp.net

File upload using HTML5's drag and drop in Asp.net

Am trying to upload a file using HTML5's DnD and File API. Am not to sure
how to send form data to the server, i tried to send using XMLHttpRequest
but was not successful. This what i have so far.
- UI
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<br />
<div id="drop_area">Drop files here</div> <br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button"/>
</form>
</body>
- Client-Side Script
<script>
if (window.File && window.FileList && window.FileReader) {
var dropZone = document.getElementById('drop_area');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleDnDFileSelect,
false);
}
else {
alert('Sorry! this browser does not support HTML5 File
APIs.');
}
</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 = XMLHttpRequest();
xhr.open("POST", "Upload.aspx"); //Wrong ? not sure.
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(data);
}
- Server Side
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile upload = fileCollection[i];
string filename ="c:\\Test\\" + upload.FileName;
upload.SaveAs(filename);
}
I know i have a button in the UI,as of now am not using. But as you can
see am trying to send a request using XMLHttpRequest. Can anyone suggest
me how can i proceed further. But my server side code never get executed
am not sure whether XMLHttpRequest was successful.
Any help is much appreciated. Thanks in advance.

No comments:

Post a Comment