Created
April 26, 2012 19:47
-
-
Save HenrikJoreteg/2502497 to your computer and use it in GitHub Desktop.
AJAX file uploading using jQuery and XMLHttpRequest 2.0 and adding listener for progress updates
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
// grab your file object from a file input | |
$('#fileInput').change(function () { | |
sendFile(this.files[0]); | |
}); | |
// can also be from a drag-from-desktop drop | |
$('dropZone')[0].ondrop = function (e) { | |
e.preventDefault(); | |
sendFile(e.dataTransfer.files[0]); | |
}; | |
function sendFile(file) { | |
$.ajax({ | |
type: 'post', | |
url: '/targeturl?name=' + file.fileName, | |
data: file, | |
success: function () { | |
// do something | |
}, | |
xhrFields: { | |
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet) | |
onprogress: function (progress) { | |
// calculate upload progress | |
var percentage = Math.floor((progress.total / progress.totalSize) * 100); | |
// log upload progress to console | |
console.log('progress', percentage); | |
if (percentage === 100) { | |
console.log('DONE!'); | |
} | |
} | |
}, | |
processData: false, | |
contentType: file.type | |
}); | |
} |
this worked for me..
$(document).ready(function() {
// grab your file object from a file input
$('#fileInput').change(function() {
sendFile(this.files);
});
function sendFile(files) {
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
console.log(data,data[0],data);
$.ajax({
type: 'post',
url: '?name=' + files.name,
data: data,
success: function() {
// do something
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function(progress) {
console.log(progress);
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: false
});
}
})
shouldnt be?
var percentComplete = (e.loaded / e.total) * 100;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
url: '/targeturl?name=' + file.fileName, ==> url: '/targeturl?name=' + file.name,