Skip to content

Instantly share code, notes, and snippets.

@noiges
Created December 21, 2012 16:21
Show Gist options
  • Save noiges/4353801 to your computer and use it in GitHub Desktop.
Save noiges/4353801 to your computer and use it in GitHub Desktop.
Async client-side drag-and-drop file upload to Amazon S3
$(function(){
$("#files").bind("change", handleFileSelection);
var dropzone = $("#dropzone");
dropzone.on("dragover",allowDrop);
dropzone.on("drop",drop);
});
function handleFileSelection(event){
upload(event.target.files);
}
function allowDrop(event){
event.preventDefault();
}
function drop(event){
event.preventDefault();
upload(event.originalEvent.dataTransfer.files);
}
function upload(files){
for (var i = 0; i < files.length; i++) {
var file = files[i];
if(file.type != "image/jpeg"){
console.log("Unsupported type of " + file.name + ": " + file.type);
continue;
}
console.log("Uploading " + file.name);
$.ajax({
type: "GET",
url: "/credentials",
cache: false,
success: function(credentials){
post(credentials, file);
},
error: function(){
console.error("Could not fetch credentials from server");
}
});
}
}
function post(credentials, file){
var formData = new FormData();
formData.append("key", credentials.key);
formData.append("acl", credentials.acl);
formData.append("Content-Type", credentials.content_type);
formData.append("AWSAccessKeyId", credentials.access_key);
formData.append("policy", credentials.policy)
formData.append("signature", credentials.signature);
formData.append("file", file);
$.ajax({
type: "POST",
url: "https://" + credentials.bucket + ".s3.amazonaws.com",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function(){
console.log(file.name + " successfully uploaded");
},
error: function(){
console.error("Could not upload " + file.name);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment