hugowan
6/13/2012 - 9:37 AM

HTML5 Ajax upload

HTML5 Ajax upload

<form>
    <input type="file" id="file" name="file">
    <input type="submit">
</form>

<script>
$('form').submit(function (e) {
	e.preventDefault();

	var data;
	data = new FormData();
	data.append( 'file', $( '#file' )[0].files[0] );

	$.ajax({
		url: 'http://www.xxx.com/upload.php',
		data: data,
		processData: false,
		contentType: false,
		type: 'POST',
		xhr: function(){
			var xhr = $.ajaxSettings.xhr();

			xhr.upload.addEventListener('progress', function(evt) {
				var percent = evt.loaded/evt.total*100;
				console.log('Upload progress: ' + percent + '%');
			}, false);

			return xhr;
		},
		success: function(data){
			alert(data);
		}							
	});
});
</script>