Skip to content

Instantly share code, notes, and snippets.

@chfritz
Created June 18, 2013 17:03
Show Gist options
  • Save chfritz/5807253 to your computer and use it in GitHub Desktop.
Save chfritz/5807253 to your computer and use it in GitHub Desktop.
If you like the file drag&drop functionality of knistr and would like to use it on your own page, you can. We are making this little piece of javascript available under the liberal MIT license. You can use it to turn any div element into a drop container, and specify a URL to upload the file to. If the server you are uploading to does something …
/*
(MIT License)
Copyright (c) 2012 Christian Fritz
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
A drop handler that can listen to drops from several DOM nodes.
Example Usage. This will turn the div with id 'dropzone' into a
drag&drop container, and will upload dropped files to "/upload".
var dh = new dragAndDropFileUpload({
onComplete: function(filename,resp,dataURL) {
if (resp.status != 200) {
alert(resp.statusText + ". " + resp.responseText);
} else {
console.log("File uploaded!");
}
},
onDrop: function() {
alert( "started upload");
},
url: "/upload",
style_normal: "rounded",
style_highlight: "rounded highlight",
style_highlight_more: "rounded highlightMore",
text: "Drop Files Here"
});
dh.add( 'dropzone' );
Example handler on the server for node.js (for parsimony here without
any exception handling):
var express = require("express");
var http = require('http');
var app = express();
var fs = require('fs');
app.post('/upload', function(req, res) {
console.log( req.files );
var dir = '/tmp/uploadedfiles/';
var reader = fs.createReadStream( req.files.filename.path );
var writer = fs.createWriteStream( dir+req.files.filename.name );
reader.pipe(writer);
res.send("File uploaded.");
});
http.createServer(app).listen(8000);
*/
function dragAndDropFileUpload(conf){
callback = conf.onComplete;
fnOnDrop = conf.onDrop;
conf.text = (conf.text || "");
var dropContainer;
this.htmlnodeid = "";
handleDrop = function(event){
dropContainer = event.target;
event.stopPropagation();
event.preventDefault();
if (fnOnDrop) {
fnOnDrop(dropContainer);
}
build(event);
return false;
};
build = function(event){
var files = event.dataTransfer.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// fetchDataURL = new FileReader();
// fetchDataURL.onloadend = function(evt){
// upload(file, event, evt.target.result);
// };
// fetchDataURL.readAsDataURL(file);
upload(file);
}
}
upload = function(file) {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {
alert('Your browser does not support AJAX!');
}
}
};
xmlHttp.onreadystatechange = function(){
$( "#fd_progress_text")
.text("Complete!");
if (xmlHttp.readyState == 4) {
$( "#fd_progress").hide();
$( "#fd_progress_text").hide();
callback(file.name, xmlHttp);
}
};
// xmlHttp.onprogress = function(a,b,c) {
// console.log(a,b,c);
// };
xmlHttp.upload.onprogress = function(a,b,c) {
var value = Math.floor((((a.loaded*100.0)/a.total) * 100)) / 100.0;
$( "#fd_progress")
.progressbar({value: value});
$( "#fd_progress_text")
.text(value + "%");
};
var url = conf.url;
// xmlHttp.setRequestHeader("Content-type", "multipart/form-data");
// xmlHttp.overrideMimeType('text/plain; charset=x-user-defined-binary');
// xmlHttp.setRequestHeader("Content-length", file.length);
// xmlHttp.setRequestHeader("Connection", "close");
// xmlHttp.send(file);
xmlHttp.open('POST', url, true);
var fd = new FormData();
fd.append('filename', file);
xmlHttp.send(fd);
console.log(xmlHttp);
$( "#fd_tr_progress")
.show();
$( "#fd_filename")
.text(file.name);
$( "#fd_progress").show();
$( "#fd_progress_text").show();
}
/**
* add another html node to allow drops on
* @param {Object} htmlnode
*/
this.add = function(htmlnodeid){
var dropContainer = document.getElementById(htmlnodeid);
this.htmlnodeid = htmlnodeid;
console.log(dropContainer);
window.addEventListener("dragenter", function(event){
document.getElementById(dropContainer.id).className = conf.style_highlight;
return false;
}, false);
dropContainer.addEventListener("dragover", function(event){
document.getElementById(dropContainer.id).className = conf.style_highlight_more;
event.stopPropagation();
event.preventDefault();
return false;
}, false);
dropContainer.addEventListener("dragexit", function(event){
document.getElementById(dropContainer.id).className = conf.style_normal;
return false;
}, false);
// window.addEventListener("dragexit", function(event){
// document.getElementById(dropContainer.id).className = conf.style_normal;
// return false;
// }, false);
dropContainer.addEventListener("drop", function(event){
document.getElementById(dropContainer.id).className = conf.style_normal;
handleDrop(event);
}, false);
$( "#"+htmlnodeid )
.append("<table style=\"width:100%; position:absolute; top: 0; left: 0;\">"+
"<tr><td id=\"fd_text\" colspan=3>"+conf.text+"</td></tr>"+
"<tr id=\"fd_tr_progress\" style=\"height: 14px; display:none\">"+
"<td id=\"fd_filename\" style=\"width: 50%; vertical-align: top; font-size: 14px\"></td>"+
"<td id=\"fd_progress\" style=\"width: 25%; height: 14px;\"></td>"+
"<td id=\"fd_progress_text\" style=\"width: 15%; vertical-align: top; text-align: center; font-size: 14px\"></td>"+
"</tr>");
$( "#"+htmlnodeid+" #fd_progress")
.progressbar({value: 0});
}
}
@chfritz
Copy link
Author

chfritz commented Nov 12, 2013

Please note that this file requires query-ui.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment