index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | //index.html <!DOCTYPE html> <html> <head> <title>JavaScript PHP upload multiple files</title> </head> <body> <div> <p><h1>JavaScript PHP upload multiple files<h1></p> <input type= "file" name= "files" id= "files" multiple> <input type= "button" id= "btn_uploadfile" value= "Upload" onclick= "uploadFile();" > </div> <script type= "text/javascript" > function uploadFile() { var totalfiles = document.getElementById( 'files' ).files.length; if (totalfiles > 0 ){ var formData = new FormData(); // Read selected files for ( var index = 0; index < totalfiles; index++) { formData.append( "files[]" , document.getElementById( 'files' ).files[index]); } var xhttp = new XMLHttpRequest(); // Set POST method and ajax file path xhttp.open( "POST" , "ajaxfile.php" , true); // call on request changes state xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var response = this.responseText; alert(response + " File uploaded." ); } }; // Send request with data xhttp.send(formData); } else { alert( "Please select a file" ); } } </script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | //ajaxfile.php <?php // Count total files $countfiles = count ( $_FILES [ 'files' ][ 'name' ]); // Upload directory $upload_location = "uploads/" ; $count = 0; for ( $i =0; $i < $countfiles ; $i ++){ // File name $filename = $_FILES [ 'files' ][ 'name' ][ $i ]; // File path $path = $upload_location . $filename ; // file extension $file_extension = pathinfo ( $path , PATHINFO_EXTENSION); $file_extension = strtolower ( $file_extension ); // Valid file extensions $valid_ext = array ( "pdf" , "doc" , "docx" , "jpg" , "png" , "jpeg" ); // Check extension if (in_array( $file_extension , $valid_ext )){ // Upload file if (move_uploaded_file( $_FILES [ 'files' ][ 'tmp_name' ][ $i ], $path )){ $count += 1; } } } echo $count ; exit ; |