Skip to content

Instantly share code, notes, and snippets.

@sagar-ganatra
Created August 12, 2012 10:08
Show Gist options
  • Save sagar-ganatra/3331044 to your computer and use it in GitHub Desktop.
Save sagar-ganatra/3331044 to your computer and use it in GitHub Desktop.
Uploading chunks of a large file using XHR2
<!DOCTYPE HTML>
<html>
<body>
<div id="uploadFile">
<input type="file" id="userfile">
<div id="messages">
</div>
</div>
<script>
(function(){
var blobs = [];
/*
* function that uploads a fragment of the file
*/
function uploadChunk(blob, fileName, fileType){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_chunks.cfm', false);
xhr.onload = function(e){
document.getElementById("messages").innerHTML += "Chunk of size " + blob.size + " uploaded successfully.<br/>";
}
xhr.setRequestHeader('X_FILE_NAME', fileName);
xhr.setRequestHeader('Content-Type', fileType)
document.getElementById("messages").innerHTML += "Uploading chunk of size " + blob.size + ".<br/>";
xhr.send(blob);
}
/*
* Invoke this function when the file is selected.
*/
document.querySelector('#userfile').addEventListener('change', function(){
var file = this.files[0];
var bytes_per_chunk = 1024 * 1024;
var start = 0;
var end = bytes_per_chunk;
var size = file.size;
while (start < size) {
//push the fragments to an array
blobs.push(file.slice(start, end));
start = end;
end = start + bytes_per_chunk;
}
//upload the fragment to the server
while (blob = blobs.shift()) {
uploadChunk(blob, file.name, file.type);
}
})
})();
</script>
</body>
</html>
<cfset headerData = getHTTPRequestData().headers>
<cfset content = getHTTPRequestData().content>
<cfset filePath = expandPath(".") & "/Uploaded/" & "#headerData.X_FILE_NAME#">
<cfset fos = createObject("java", "java.io.FileOutputStream").init(filePath, true)>
<cfset fos.write(content)>
<cfset fos.close()>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment