Created
May 23, 2012 16:50
-
-
Save futjikato/2776320 to your computer and use it in GitHub Desktop.
Codesnippet for chunked fileupload via socket.io and js file api ( clientside )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
// Check for the various File API support. | |
if (window.File && window.FileReader && window.FileList && window.Blob) { | |
var file = $('#file').get(0).files[0]; | |
if(file.type.search(/^audio\//) == -1) { | |
alert('Please upload an audio file.'); | |
} | |
// change | |
window.location.hash = '#!newEpisode/upload'; | |
// read audio file | |
var reader = new FileReader(); | |
// event triggered wghen the file is loaded | |
reader.onload = function(fev) { | |
var chunkIndex = 0; // current index to start rading file | |
var chunkIndexEnd = chunkIndex + 5000; // send 5000 bits per message | |
var fileBiteLength = fev.target.result.length; | |
// called when the server is ready to get the data | |
episodeSock.once('serverUploadReady', function(){ | |
var isEnd = false; | |
if(chunkIndexEnd >= fileBiteLength) { | |
chunkIndexEnd -= (chunkIndexEnd - fileBiteLength); | |
isEnd = true; | |
} | |
var chunk = fev.target.result.slice(chunkIndex, chunkIndexEnd); | |
chunkIndex += chunkIndexEnd; // increment current file pointer | |
chunkIndexEnd += 5000; // send 5000 bits per message | |
episodeSock.emit('clientUplaodChunk', { | |
chunk : chunk, | |
end : isEnd | |
}); | |
}); | |
// called when the server has recieved a complete file and is ready for the metadata | |
episodeSock.once('serverUploadComplete', function(data){ | |
episodeSock.emit('add', { | |
sid : sid, | |
name : $('#name').val(), | |
description : $('#description').val(), | |
file : data.fileid | |
}); | |
}); | |
// send notice to server that a fileupload is coming in | |
episodeSock.emit('clientUplaodReady', { | |
sid : sid, | |
filename : file.name | |
}); | |
}; | |
reader.readAsBinaryString(file); | |
} else { | |
alert('Sorry, but you need a moder browser with file api to upload files.'); | |
} | |
} catch(e) { | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment