Upload.php :
<?php
$filename = $_FILES['file']['name'];
$location = "Image/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$valid_extensions = array("jpg","jpeg","png");
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
$uploadOk = 0;
}if($uploadOk == 0){
echo 0;
}else{
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
echo $location;
}else{
echo 0;
}
}
?>
Index.php :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<style>
/* Container */
.container{
margin: 0 auto;
border: 0px solid black;
width: 50%;
height: 250px;
border-radius: 3px;
background-color: ghostwhite;
text-align: center;
}
/* Preview */
.preview{
width: 100px;
height: 100px;
border: 1px solid black;
margin: 0 auto;
background: white;
}.preview img{
display: none;
}
/* Button */
.button{
border: 0px;
background-color: deepskyblue;
color: white;
padding: 5px 15px;
margin-left: 10px;
}
</style>
<div class="container">
<form enctype="multipart/form-data" id="myform">
<div class='preview'>
<img src="" id="img" width="100" height="100">
</div>
<div >
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
for(var i=0;i<$('#file')[0].files.length;i++){
var fd = new FormData();
var files = $('#file')[0].files[i];
fd.append('file',files);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}
});
});
</script>