Hello guys,
After a long time, I am back with this new amazing tutorial that is how to upload multiple files using jquery ajax in PHP so let’s get started.
At first in my project directory there is 2 files index.php and upload.php and one folder in upload where the uploaded files will be stored. I am showing you my scripts to do that. Copy the hole code and try to customise yourself.
index.php
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="jumbotron text-center"> <h1>Multiple Image Upload </h1> <p>Using Simple Jquery Ajax In PHP</p> </div> <div class="container"> <div class="row"> <form action="upload.php" method="post" id="upload_form"> <div class="col-md-6"> <input type="file" class="form-control" name="files[]" multiple> </div> <div class="col-md-6"> <button class="btn btn-primary">Submit</button> </div> </form> </div> <div class="row" id="output"> </div> </div> </body> </html>
Add this below script at the head tag of index.php
<script> jQuery(document).ready(function() { $('#upload_form').submit(function(e) { e.preventDefault(); $.ajax({ url: 'upload.php', type: 'post', data: new FormData(this), contentType: false, processData: false, success: function(result){ $('#output').html(result); } }); }); }); </script>
And in upload.php try this code.
<?php $result = ''; if(is_array($_FILES)) { foreach ($_FILES['files']['name'] as $name => $value) { $my_file_name = explode(".", $_FILES['files']['name'][$name]); $extension_name = array("jpg", "jpeg", "png", "gif"); if(in_array($my_file_name[1], $extension_name)) { $NewImageName = md5(rand()) . '.' . $my_file_name[1]; $SourcePath = $_FILES['files']['tmp_name'][$name]; $TargetPath = "upload/".$NewImageName; if(move_uploaded_file($SourcePath, $TargetPath)) { $result .= '<div class="col-md-4"><img src="'.$TargetPath.'" class="img-responsive"></div>'; } } } echo $result; } ?>
And now run this program and see what happend next.
Related posts