Created
February 26, 2018 13:23
-
-
Save fabriciofmsilva/fb1dcf037538d80af50a1d0f2e9c2a1c to your computer and use it in GitHub Desktop.
Upload File with jQuery + FormData
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Upload = function (file) { | |
this.file = file; | |
}; | |
Upload.prototype.getType = function() { | |
return this.file.type; | |
}; | |
Upload.prototype.getSize = function() { | |
return this.file.size; | |
}; | |
Upload.prototype.getName = function() { | |
return this.file.name; | |
}; | |
Upload.prototype.doUpload = function () { | |
var that = this; | |
var formData = new FormData(); | |
// add assoc key values, this will be posts values | |
formData.append("file", this.file, this.getName()); | |
formData.append("upload_file", true); | |
$.ajax({ | |
type: "POST", | |
url: "script", | |
xhr: function () { | |
var myXhr = $.ajaxSettings.xhr(); | |
if (myXhr.upload) { | |
myXhr.upload.addEventListener('progress', that.progressHandling, false); | |
} | |
return myXhr; | |
}, | |
success: function (data) { | |
// your callback here | |
}, | |
error: function (error) { | |
// handle error | |
}, | |
async: true, | |
data: formData, | |
cache: false, | |
contentType: false, | |
processData: false, | |
timeout: 60000 | |
}); | |
}; | |
Upload.prototype.progressHandling = function (event) { | |
var percent = 0; | |
var position = event.loaded || event.position; | |
var total = event.total; | |
var progress_bar_id = "#progress-wrp"; | |
if (event.lengthComputable) { | |
percent = Math.ceil(position / total * 100); | |
} | |
// update progressbars classes so it fits your code | |
$(progress_bar_id + " .progress-bar").css("width", +percent + "%"); | |
$(progress_bar_id + " .status").text(percent + "%"); | |
}; | |
// Source: https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment