Drag and Drop File Upload and Processing via File API

Here’s one way you could go about the drag and drop file upload and parsing for coordinates ala ArcGIS Online.

Note: You must view the demo page from a web server - file:// won’t work.

Other helpful links:
http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/
http://www.html5rocks.com/en/tutorials/file/dndfiles/

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>

<html>
<head>
<title>Page Title</title>

<style>
div { border-radius: 20px; margin-bottom: 10px; padding: 15px; }
#wrapper { margin: 20px auto; max-width: 600px; }
#dropper { border: 5px dashed #ccc; height: 100px; text-align: center; font-size: 60px; color: #ccc; }

#fileinfo { border: 5px solid black; height: 30px; }
#filedata { border: 5px solid black; height: 250px; }
</style>
</head>

<body>

<div id="wrapper">
<div id="dropper">Drop File Here</div>
<div id="fileinfo">File Info</div>
<div id="filedata">File Data</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="script.js"></script>

</body>
</html>

script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
$(document).ready(function() {
var dropbox = document.getElementById("dropper");

dropbox.addEventListener("dragover", dragOver, false);
dropbox.addEventListener("drop", drop, false);

});

function dragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
}

function drop(evt) {
evt.stopPropagation();
evt.preventDefault();

var files = evt.dataTransfer.files;

if (files.length > 0) handleFiles(files);
}


function handleFiles(files) {
var f = files[0];
var output = [];
output.push('<strong>', f.name, '</strong> (', f.type || 'n/a', ') - ', f.size, ' bytes');

$("#fileinfo").html(output.join(""));

var reader = new FileReader();
reader.onloadend = handleReaderLoadEnd;
reader.readAsText(f);

}

function handleReaderLoadEnd(evt) {
lines = evt.target.result.split(/\r\n|\r|\n/);

coords = [];

for(i=0; i < lines.length; i++) {
var line = lines[i].split(",");
if (line.length > 1 &amp;&amp; !isNaN(line[0]) &amp;&amp; !isNaN(line[1])) {
coords[coords.length]= line[0] + "," + line[1];
}
}

$("#filedata").empty();

$.each(coords, function(index, value){
$("#filedata").append(value + "<br />");
});

}