Introduction:
In this tutorial learn how to make a stunning looking file upload without any page refresh or even it doesn't need button click, just choose a file and it will be uploaded.
Demo:
Step to Follow :
Downlaod The JQuery File and paste it to your project folder create files for below codes, and you are all ok.
upload_image.php
<!doctype html>
<html>
<style>
*{margin:0px; padding:0px;}
#container{width:20%; padding:2%; box-shadow:0px 0px 10px #888888; margin:10px auto;}
#image1{width:96% ; padding:2%; border:1px dashed green;}
#header{background:#405570; color:white;text-align:center; padding:2%;}
#view-image{border-radius:5px; overflow:hidden;}
#preview-image{padding:1%; border:1px solid #efefef; height:200px;}
</style>
<body>
<div id="container">
<form method="post" action="upload_file.php" enctype="multipart/form-data">
<input type="file" id="image" />
</form>
<br>
<div id="view-image">
<h3 id="header">Preview Image</h3>
<div id="preview-image">
image will show right here
</div>
</div>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$('#image').change(function(){
var data = new FormData() ;
data.append('file', $( '#image' )[0].files[0]) ;
$.ajax({
url: 'upload_file.php',
type: 'POST',
data: data,
processData: false,
contentType: false,
beforeSend: function(){
$('#preview-image').html('Loading...');
},
success: function(data){
// alert(data);
$('#preview-image').html('<img src="'+data+'" style="width:100%"/>');
}
});
return false;
});
});
</script>
</body>
</html>
upload_file.php
<?php
if(isset($_FILES['file'])){
$file = $_FILES['file'] ;
$error = $file['error'];
$name= $file['name'] ;
$tmp_name = $file['tmp_name'] ;
$size = $file['size'] ;
if($error == 0){
//type restriction
$ext = explode(".", $name) ;
$ext = end($ext) ;
$ext = strtolower($ext ) ;
$allow = array("jpg", "png") ;
if(in_array($ext, $allow)){
// check file size
if($size <= 2000000){
//check wether file uploaded or not
if(move_uploaded_file( $tmp_name, $name)){
echo $name ;
}else{
echo 'file not uploaded' ;
}
}else{
echo 'File is too big' ;
}
}else{
echo 'Type not allowed';
}
}else{
echo 'error in file';
}
}
?>
if(isset($_FILES['file'])){
$file = $_FILES['file'] ;
$error = $file['error'];
$name= $file['name'] ;
$tmp_name = $file['tmp_name'] ;
$size = $file['size'] ;
if($error == 0){
//type restriction
$ext = explode(".", $name) ;
$ext = end($ext) ;
$ext = strtolower($ext ) ;
$allow = array("jpg", "png") ;
if(in_array($ext, $allow)){
// check file size
if($size <= 2000000){
//check wether file uploaded or not
if(move_uploaded_file( $tmp_name, $name)){
echo $name ;
}else{
echo 'file not uploaded' ;
}
}else{
echo 'File is too big' ;
}
}else{
echo 'Type not allowed';
}
}else{
echo 'error in file';
}
}
?>
Very helpful
ReplyDelete