Skip to content

Instantly share code, notes, and snippets.

@dgs700
Created March 29, 2012 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgs700/2244421 to your computer and use it in GitHub Desktop.
Save dgs700/2244421 to your computer and use it in GitHub Desktop.
Production AJAX avatar image and file uploader in use at StudentMentor.org. Based on jQuery and jQuery.Fileupload.
define(['underscore', 'cookie', 'fileupload', 'widget', 'iframe'], function(){
return {
// call from page specific context w/ config obj that defines
// a script or div element containing page specific html (templateID), location to insert
// processed template (targetID) and an obj (vars) defining any variable placeholders
renderUploadContainer: function(config){
var vars = config.vars || {},
templateID = config.templateID || null,
targetID = config.targetID || null,
template;
if( typeof templateID == "string" && typeof targetID == "string"){
template = _.template($(templateID).html(), vars);
$(targetID).replaceWith(template);
return true;
} else {
return false;
}
},
// need to decide on actual defaults for an api
fileUploadSM: function(config){
// common parameters and defaults
var eid = config.eid || '#upload_file_element', //id of input type=file element
//the default for responseId should eventually probably be to create and insert an element if none provided
responseId = config.responseId || '#upload_response_element', // where success/failure mssgs go
fileFacadeId = config.fileFacadeId || '#avatar_facade',
uploadButtonId = config.uploadButtonId || null,
progressId = config.progressId || null,
url = config.url || '', // undecided what the default will be
dataType = config.dataType || 'json', // may need to be text due to IE bs
includeFormData = config.includeFormData || false, // option to post any other data from an enclosing form
noAutoUpload = config.noAutoUpload || false, // upload file on selection, true to bind upload to button click
//initialize the ajax uploader
uploader = $(eid).fileupload({ //return the initialized uploader should we desire to bind or alter down the road
url: url,
dataType: dataType,
formData: function(form){
if(includeFormData){
return form.serializeArray();
}else{
// to post additional programatically include something like the following
//return [{name:'userID', value:'100'},{name:'fieldnamne',value'fieldvalue'}];
return [];
}
},
//(some) callbacks, page agnostic stuff can go in these
//override these in page code for page dependent actions
change: function(event, data){},
// data.submit() is where the req is kicked off
// unfortunately there is no exposed way to intercept and bind to a button click easily
add: function(event, data){
//global1 = data;
if(noAutoUpload == true && uploadButtonId){
var $fileFacade = $(fileFacadeId);
$fileFacade.val(data.fileInput.val());
$(uploadButtonId).one('click', function(){
data.submit();
$fileFacade.val('');
});
} else {
data.submit();
}
},
// return false to cancel submit()
submit: function(event, data){
$(responseId).hide();
},
// return false to abort upload
send: function(event, data){
$(progressId).show();
},
// called if a JSON response is received
// this should be defined and bound from the page specific context
// since it is where page specific stuff is performed
// all "done" callbacks should test for success or error objects
done: function(event, data){
// if(data.result.success instanceof Object){}
// else if (data.result.error instanceof Object){}
},
//this is NOT called if the server returns a json error response
fail: function(event, data){
$(responseId).text(
config.jqXHRerrorHandler(data.jqXHR, data.textStatus, data.errorThrown)
).show();
},
// code to execute on either success or failure
always: function(event, data){
$(progressId).hide();
}
});
// return a handle for further binding and manipulation in page code
return uploader;
},
jqXHRerrorHandler: function(jqXHR, textStatus, error){
if(jqXHR.status==0){
return 'Error: You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
return 'Error: Requested URL not found.';
}else if(jqXHR.status==403){
return 'Error: Restricted access.';
}else if(jqXHR.status==500){
return 'Error: Internel Server Error.';
} else if(jqXHR.status==413){
return 'Error: File larger than 2MB.';
}else if(textStatus=='parsererror'){
return 'Error: Parsing JSON Request failed.';
}else if(textStatus=='timeout'){
return 'Error: Request Time out.';
}else {
return 'Unknow Error.\n' + jqXHR.responseText;
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment