Skip to content

Instantly share code, notes, and snippets.

@fabiosussetto
Created January 6, 2012 17:48
Show Gist options
  • Save fabiosussetto/1571632 to your computer and use it in GitHub Desktop.
Save fabiosussetto/1571632 to your computer and use it in GitHub Desktop.
Ajax file upload
/*
* Ajax file upload experiment
*/
AjaxUploadHandler = function(o){
this._options = {
action: '/upload.php',
onProgress: function(fileName, loaded, total){},
onComplete: function(fileName, response){},
onCancel: function(id, fileName){}
};
$.extend(this._options, o);
this._file = null;
this._xhr = null;
this._loaded = 0;
};
$.extend(AjaxUploadHandler.prototype, {
setFile: function(file){
if (!(file instanceof File)){
throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
}
this._file = file;
},
getName: function(){
return this._file.fileName != null ? this._file.fileName : this._file.name;
},
getSize: function(id){
return this._file.fileSize != null ? this._file.fileSize : this._file.size;
},
getLoaded: function(id){
return this._loaded || 0;
},
upload: function(params){
var file = this._file,
name = this.getName(),
size = this.getSize();
this._loaded = 0;
var xhr = this._xhr = new XMLHttpRequest();
var self = this;
xhr.upload.onprogress = function(e){
if (e.lengthComputable){
self._loaded = e.loaded;
self._options.onProgress(name, e.loaded, e.total);
}
};
xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
self._onComplete(xhr);
}
};
// build query string
params = params || {};
params['file'] = name;
var queryString = this._options.action + '&' + $.param(params);
console.debug('params: ' + $.param(params));
console.debug('querystring: ' + queryString);
xhr.open("POST", this._options.action, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
},
_onComplete: function(xhr){
if (!this._file) return;
var name = this.getName();
var size = this.getSize();
this._options.onProgress(name, size, size);
if (xhr.status == 200){
this.log("xhr - server response received");
this.log("responseText = " + xhr.responseText);
var response;
try {
response = eval("(" + xhr.responseText + ")");
} catch(err){
response = {};
}
this._options.onComplete(name, response);
} else {
this._options.onComplete(name, {});
}
this._file = null;
},
_cancel: function(id){
this._options.onCancel(this.getName());
this._file = null;
if (this._xhr){
this._xhr.abort();
this._xhr = null;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment