Skip to content

Instantly share code, notes, and snippets.

@brayoh
Last active May 4, 2016 21:52
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 brayoh/d0cd0be3bc5ea3ff8eb9b900e8684f20 to your computer and use it in GitHub Desktop.
Save brayoh/d0cd0be3bc5ea3ff8eb9b900e8684f20 to your computer and use it in GitHub Desktop.
image upload using xhr request
$(function(){
'use strict';
$('#your-form').submit(function(ev){
ev.preventDefault();
// Create a new FormData object.
var formData = new FormData();
var files = document.getElementById('your-file-input').files;
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
// continue;
}
// Files
formData.append('image', file, file.name);
}
// Set up the request.
var xhr = new XMLHttpRequest();
// Set up a handler for when the request finishes.
xhr.upload.addEventListener('loadstart', function(e) {
// When the request starts.
console.log("xhr loaded");
});
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percent = (e.loaded / e.total) * 100;
console.log(percent);
}
});
xhr.upload.addEventListener('load', function(e) {
// When the request has *successfully* completed.
// Even if the server hasn't responded that it finished.
console.log("request successfully completed");
});
xhr.upload.addEventListener('loadend', function(e) {
// When the request has completed (either in success or failure).
// Just like 'load', even if the server hasn't
// responded that it finished processing the request.
console.log("request completed");
});
xhr.upload.addEventListener('error', function(e) {
// When the request has failed.
console.log("error occured");
});
xhr.upload.addEventListener('abort', function(e) {
// When the request has been aborted.
// For instance, by invoking the abort() method.
console.log("process aborted");
});
xhr.upload.addEventListener('timeout', function(e) {
// When the author specified timeout has passed
// before the request could complete.
console.log("server timeout");
});
// notice that the event handler is on xhr and not xhr.upload
// Open the connection.
xhr.open('POST', 'your-upload-url', true);
xhr.send(formData);
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 && xhr.status == 200 ) {
// the transfer has completed and the server closed the connection.
console.log("transfer completed");
submitForm(xhr.responseText);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment