Skip to content

Instantly share code, notes, and snippets.

@dannvix
Created February 25, 2011 17:48
Show Gist options
  • Save dannvix/844183 to your computer and use it in GitHub Desktop.
Save dannvix/844183 to your computer and use it in GitHub Desktop.
Example Rails view with mod_upload_progress
<% uuid = (rand * 1e10).floor %>
<script type="text/javascript">
var timer;
var elapsed;
function update_progress() {
elapsed += 1;
jQuery.ajax({
type: "GET",
url: "/progress",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Progress-ID", <%= uuid %>);
},
success: function(upload) {
$("body").append(upload.state);
if (upload.state == 'uploading') {
$("#status").html("Uploading... " + Math.floor(upload.received/1024) + " / " + Math.floor(upload.size/1024) + " KB (" + Math.floor((upload.received / upload.size) * 100) + "%) " + Math.floor((upload.received/1024)/elapsed) + "KB/s, ETA: " + Math.floor((upload.size - upload.received)/((upload.received)/elapsed)) + " sec");
}
if (upload.state == 'error') {
$("#status").html("Error: " + upload.status);
window.clearTimeout(timer);
}
if (upload.state == 'done') {
$("#status").html("Done.");
window.clearTimeout(timer);
}
}
});
}
</script>
X-Progress-ID: <%= uuid %><br />
<span id="status"></span><br />
<form id="upload" action="/save?X-Progress-ID=<%= uuid %>" method="post" enctype="multipart/form-data" target="upload_proxy">
<input type="file" name="upload" />
<input type="hidden" id="token" />
<input type="submit" value="upload" />
<iframe id="upload_proxy" style="position: absolute; top: -999999px;"></iframe>
</form>
<script type="text/javascript">
$("input#token").attr("name", $("meta[name=csrf-param]").attr("content"));
$("input#token").val($("meta[name=csrf-token]").attr("content"));
jQuery("form#upload input[type=submit]").click(function(){
elapsed = -1;
timer = window.setInterval(function(){update_progress();}, 1000);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment