Skip to content

Instantly share code, notes, and snippets.

@boazsender
Created December 20, 2010 15:44
Show Gist options
  • Save boazsender/748534 to your computer and use it in GitHub Desktop.
Save boazsender/748534 to your computer and use it in GitHub Desktop.
// Originally solved by Tim Branyen in his drop file plugin
// http://dev.aboutnerd.com/jQuery.dropFile/jquery.dropFile.js
jQuery.event.props.push('dataTransfer');
var body = document.getElementByTagname('body')[0];
body.addEventListener('dragenter', function( event ) {
// event is a reference to the event object
// created for each event that triggers this callback
// in a 'drop' event, event.dataTransfer.files is a FileList
// of dropped files
}, false);
jQuery(function(){
var body = jQuery('body')
.bind( 'dragenter dragover', false)
.bind( 'drop', function( e ) {
e.stopPropagation();
e.preventDefault();
jQuery.each( e.dataTransfer.files, function(index, file){
var fileReader = new FileReader();
fileReader.onload = (function(file) {
return function(e) {
body.append('<div class="dataurl"><strong>' + file.fileName + '</strong>' + e.target.result + '</div>')
};
})(file);
fileReader.readAsDataURL(file);
});
});
});
<!DOCTYPE html>
<html>
<head>
<title>File Converter</title>
<script src="http://code.jquery.com/jquery.js"></script>
<style>
body {min-height: 800px;}
</style>
<script type="text/javascript">
jQuery(function(){
// jQuery creates it's own event object, and it doesn't have a
// dataTransfer property yet. This adds dataTransfer to the event object.
// Thanks to l4rk for figuring this out!
jQuery.event.props.push('dataTransfer');
var body = jQuery('body')
.bind( 'dragenter dragover', false)
.bind( 'drop', function( e ) {
e.stopPropagation();
e.preventDefault();
body.html("<h2>You're welcome ;)</h2>")
jQuery.each( e.dataTransfer.files, function(index, file){
var fileReader = new FileReader();
fileReader.onload = (function(file) {
return function(e) {
body.append('<div class="dataurl"><strong>' + file.fileName + '</strong>' + e.target.result + '</div>')
};
})(file);
fileReader.readAsDataURL(file);
});
});
});
</script>
</head>
<body>
<h1>Drop one or more files here to convert them to <a href="https://developer.mozilla.org/en/DOM/FileReader#section_10">Data URLs</a></h1>
</body>
</html>
function eventHandler ( event ) {
var myFileReader = new FileReader(),
myFile = e.dataTransfer.files[0]
console.log( myFileReader.readAsDataURL( myFile ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment