Skip to content

Instantly share code, notes, and snippets.

@eltonmarques96
Forked from umidjons/index.html
Created February 5, 2020 02:21
Show Gist options
  • Save eltonmarques96/3a6058d1a2f66c56d226f9ba9e34f78f to your computer and use it in GitHub Desktop.
Save eltonmarques96/3a6058d1a2f66c56d226f9ba9e34f78f 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment