Skip to content

Instantly share code, notes, and snippets.

@pangratz
Forked from noiges/upload.js
Last active December 10, 2015 00:49
Show Gist options
  • Save pangratz/4353806 to your computer and use it in GitHub Desktop.
Save pangratz/4353806 to your computer and use it in GitHub Desktop.
$(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);
(function(leFile) {
$.ajax({
type: "GET",
url: "/credentials",
cache: false,
success: function(credentials){
post(credentials, leFile);
},
error: function(){
console.error("Could not fetch credentials from server");
}
});
})(file);
}
}
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);
}
});
}
@noiges
Copy link

noiges commented Dec 21, 2012

Thank you pangratz! Closures FTW!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment