Below the code, explain that upload multiples files by jQuery Ajax and move files using Form Data to created different folders by PHP move_uploaded_file function. Created multiple folders by time function and create random numbers for the rand function.
HTML code for creating form input file and button to upload files.
HTML Code :
<div id="uploadMultipleFile"> <div><input type="file" multiple id="uploadMultiple" name="uploadMultiple"/></div> <div><button id="uploadMultipleFiles">Upload Files</button></div> </div>
Ajax and jQuery Code:
Ajax code with use form data to store files and send files to PHP file
jQuery(document).ready(function(){ jQuery('#uploadMultipleFiles').click(function(){ var form = new FormData(); for(var i = 0; i < jQuery('#uploadMultiple').get(0).files.length ; i++ ){ form.append('files[]', jQuery('#uploadMultiple').get(0).files[i]); } console.log(form); $.ajax({ url: 'upload.php', cache: false, contentType: false, processData: false, data: form, type: 'post', success: function (response) { console.log(response); } }); }); });
PHP Code
<?php if(isset($_FILES['files'])){ $no_files = count($_FILES["files"]['name']); //echo $no_files; $t = date("dmygis"); $rand = rand(1, 20); echo 'upload/'.$t.$rand; $folderName = 'upload/'.$t.$rand; mkdir($folderName); for ($i = 0; $i < $no_files; $i++) { if ($_FILES["files"]["error"][$i] > 0) { echo "Error: " . $_FILES["files"]["error"][$i] . "<br>"; } else { move_uploaded_file($_FILES["files"]["tmp_name"][$i], $folderName.'/'.$_FILES["files"]["name"][$i]); } } } ?>