Skip to content

Instantly share code, notes, and snippets.

@umidjons
Last active January 6, 2024 18:46
Show Gist options
  • Save umidjons/6173837 to your computer and use it in GitHub Desktop.
Save umidjons/6173837 to your computer and use it in GitHub Desktop.
Upload File using jQuery.ajax() with progress support
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File using jQuery.ajax() with progress support</title>
</head>
<body>
<input type="file" name="file" id="sel-file"/>
<button id="send">Send</button>
<script src="jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery( document ).ready( function ()
{
$( '#send' ).on( 'click', function ()
{
var file = $( '#sel-file' ).get( 0 ).files[0],
formData = new FormData();
formData.append( 'file', file );
console.log( file );
$.ajax( {
url : 'save-file.php',
type : 'POST',
contentType: false,
cache : false,
processData: false,
data : formData,
xhr : function ()
{
var jqXHR = null;
if ( window.ActiveXObject )
{
jqXHR = new window.ActiveXObject( "Microsoft.XMLHTTP" );
}
else
{
jqXHR = new window.XMLHttpRequest();
}
//Upload progress
jqXHR.upload.addEventListener( "progress", function ( evt )
{
if ( evt.lengthComputable )
{
var percentComplete = Math.round( (evt.loaded * 100) / evt.total );
//Do something with upload progress
console.log( 'Uploaded percent', percentComplete );
}
}, false );
//Download progress
jqXHR.addEventListener( "progress", function ( evt )
{
if ( evt.lengthComputable )
{
var percentComplete = Math.round( (evt.loaded * 100) / evt.total );
//Do something with download progress
console.log( 'Downloaded percent', percentComplete );
}
}, false );
return jqXHR;
},
success : function ( data )
{
//Do something success-ish
console.log( 'Completed.' );
}
} );
} );
} );
</script>
</body>
</html>
<?php
date_default_timezone_set( 'Asia/Tashkent' );
user_error( print_r( $_FILES, true ) );
$uploads_dir = 'uploads/';
$target_path = $uploads_dir . basename( $_FILES[ 'file' ][ 'name' ] );
if ( move_uploaded_file( $_FILES[ 'file' ][ 'tmp_name' ], $target_path ) )
{
echo 'File uploaded: ' . $target_path;
}
else
{
echo 'Error in uploading file ' . $target_path;
}
@fennecinspace
Copy link

I LOVE YOU T-T

@danyal14
Copy link

Good example 👍

@RahulSaini91
Copy link

nice work

@atakangah
Copy link

You have so saved me today!

@mbfakourii
Copy link

i love you 👍

@yanhoffmandev
Copy link

Thank you! Great job!

@watskumara
Copy link

Excellent bro

@reandimo
Copy link

reandimo commented Mar 23, 2019

Best gist ever!!! hahahha made my day!

@aliriaz186
Copy link

Great. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment