public
anonymous / gist:992562
Created

  • Download Gist
gistfile1.txt
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
Drupal.behaviors.mike_files = function () {
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);
dropZone.addEventListener('drop', handleFileSelect, false);
}
 
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
$("#drop_zone").css("background-color","green");
}
 
function handleDragLeave(evt) {
$("#drop_zone").css("background-color","white");
}
 
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
window.prepFiles = new Array();
window.fileCount = 0;
window.prepCount = 0;
for (var i = 0, f; f = files[i]; i++) {
window.fileCount += 1;
}
for (var i = 0, f; f = files[i]; i++) {
window.prepFiles[i] = new Array();
window.prepFiles[i]['filename'] = f.fileName;
window.prepFiles[i]['mimetype'] = f.type;
var reader = new FileReader();
reader.onload = function(evt) {
window.prepFiles[window.prepCount]['binary'] = evt.target.result
window.prepCount += 1;
if (window.prepCount == window.fileCount) {
buildPost();
}
}
reader.readAsBinaryString(f);
}
}
function buildPost() {
var boundary = '------multipartformboundary' + (new Date).getTime();
var dashdash = '--';
var crlf = '\r\n';
 
/* Build RFC2388 string. */
var builder = '';
 
builder += dashdash;
builder += boundary;
builder += crlf;
var xhr = new XMLHttpRequest();
for (var i = 0, f; f = window.prepFiles[i]; i++) {
builder += 'Content-Disposition: form-data; name="user_file[]"';
builder += '; filename="' + f['filename'] + '"';
builder += crlf;
builder += 'Content-Type: ' + f['mimetype'] + '';
builder += crlf;
builder += crlf;
builder += f['binary'];
builder += crlf;
 
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
}
/* Mark end of the request. */
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
xhr.open("POST", "/mike_files_upload", true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.send(builder);
xhr.onload = function(event) {
/* If we got an error display it. */
if (xhr.responseText) {
alert(xhr.responseText);
}
};
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.