Skip to content

Instantly share code, notes, and snippets.

@rudyryk
Created December 2, 2015 17:28
Show Gist options
  • Save rudyryk/d8cc5abcaaf44d95bb8c to your computer and use it in GitHub Desktop.
Save rudyryk/d8cc5abcaaf44d95bb8c to your computer and use it in GitHub Desktop.
Draft jQuery plugin for drag'n'drop uploader with PUT octet-stream request
/*!
Stream signle file upload with PUT octet-stream request.
(c) 2015 Alexey Kinev <[email protected]>
The MIT License, https://opensource.org/licenses/MIT
*/
(function ( $ ) {
$.fn.putUpload = function( opts ) {
var el = $( this );
el.on( 'dragdrop drop' , function( e ) {
var file = e.originalEvent.dataTransfer.files[0];
e.stopPropagation();
e.preventDefault();
var xhr = new XMLHttpRequest();
doUpload( el, xhr, file, opts );
});
el.on('dragenter',function( e ) {
e.preventDefault();
})
.on('dragleave',function( e ) {
e.preventDefault();
})
.on('dragover',function( e ) {
e.preventDefault();
})
.on( 'click', function ( e ) {
e.preventDefault();
doFileInput( el, opts );
});
return el;
}
function doFileInput( el, opts ) {
var fileInput = el.find('input[type="file"]');
if (fileInput.length > 1) {
fileInput = fileInput.first();
} else if (fileInput.length == 0) {
fileInput = $('<input type="file" style="visibility: hidden; height: 0px; width: 0px;">');
if (opts.accept) {
fileInput.attr( 'accept', opts.accept );
}
el.append(fileInput);
}
fileInput.on ( 'click', function ( e ) {
e.stopPropagation();
})
.on ( 'change', function ( e ) {
var xhr = new XMLHttpRequest();
doUpload( el, xhr, this.files[0], opts );
});
fileInput.click();
}
function doUpload( el, xhr, file, opts ) {
xhr.open("PUT", opts.url, true);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.fileName));
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.onreadystatechange = function(e) {
if ( xhr.readyState == 4 ) {
if ( opts.success ) {
opts.success( xhr.responseText );
}
}
}
xhr.upload.onprogress = function(e) {
if ( e.lengthComputable ) {
if ( opts.progress ) {
opts.progress( e );
}
}
}
el.trigger('startupload', xhr);
xhr.send( file );
}
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment