HTML accompanies different kinds of inputs like text, password, email, and so forth and all of these information sources are for forms. There is input type “file” which is for uploading a file, we simply need to put a tag to making this. Of course, it accompanies essential styles yet we can modify its style and function by utilizing JS and CSS. In this article, we’ll show you how to create a custom file input to preview image before uploading using jQuery and CSS.

Image Preview Feature

custom file input for image upload using jquery and css

The preview image feature lets the clients see the chosen picture before uploading. With this component, the picture is shown on the website page quickly once a file (image) is chosen by an input field. Verifying the picture before uploading is an extremely valuable component for the file transfer usefulness.

This feature helps the client to ensure before uploading the file and change the picked image if necessary. From the client’s point of view, it is useful for uploading an ideal picture or file without doing the monotonous uploading.

Steps To Create Custom Input To Preview Image Before Uploading

In this program, we will tell you the best way to show a preview image before uploading using jQuery.

For making this program you need to make 3 files. The first is for HTML, the second is for CSS, and the third for JavaScript. Follow the steps as shown below:

1. Create HTML Form For Uploading Image File

First, we create an Index File to make an HTML form. We also need to link our JS and CSS files in the index file for the styling and functioning of our program. Now copy the code below and paste it in your index file:

<html lang="en" >
<head>
  <meta charset="UTF-8">
    <title>Image Upload Preview | howto-solution.com</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css'>
  <link rel="stylesheet" href="./style.css">
 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script  src="./function.js"></script>
</head>
<body>

<div class="contain animated bounce">
<form id="form1" runat="server">
    <div class="alert"></div>
    <div id='img_contain'><img id="blah" align='middle' src="http://www.clker.com/cliparts/c/W/h/n/P/W/generic-image-file-icon-hi.png" alt="your image" title=''/></div> 
    <div class="input-group"> 
    <div class="custom-file">
    <input type="file" id="inputGroupFile01" class="imgInp custom-file-input" aria-describedby="inputGroupFileAddon01">
    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
    </div>
    </div>
</form>
</div>

</body>
</html>

2. Create CSS File For Styling Elements

The CSS file is created for styling our elements and to provide the values like padding, margins, position, etc. Now simply create a CSS file and copy-paste the code below:

}
.contain{
  margin-left:auto;
  margin-right:auto;  
  margin-top:calc(calc(100vh - 405px)/2);
}
#form1{
  width:auto;
}
.alert{
  text-align:center;
}

#blah{  
  max-height:256px;
  height:auto;
  width:auto;
  display:block;
  margin-left: auto;
   margin-right: auto;
  padding:5px;
}
#img_contain{
  border-radius:5px;
  /*  border:1px solid grey;*/
  margin-top:20px;
  width:auto;  
}
.input-group{  
  margin-left:calc(calc(100vw - 320px)/2);
  margin-top:40px;
  width:320px;
}
.imgInp{  
  width:150px;
  margin-top:10px;
  padding:10px;
  background-color:#d3d3d3;  
}
.loading{
   animation:blinkingText ease 2.5s infinite;
}
@keyframes blinkingText{
    0%{     color: #000;    }     
    50%{   color: #transparent; }
    99%{    color:transparent;  }
    100%{ color:#000; }
}
.custom-file-label{
  cursor:pointer;
}

3. Create The Javascript File To Handle The Image

It is one of the most important step, as from here we’ll be handling the program to function accordingly. Create a JS file and copy-paste the code given below:

$("#inputGroupFile01").change(function(event)
{  
  RecurFadeIn();
  readURL(this);    
});

$("#inputGroupFile01").on('click',function(event){
  RecurFadeIn();
});

function readURL(input)
{    
 if (input.files && input.files[0])
      {   
        var reader = new FileReader();
        var filename = $("#inputGroupFile01").val();
        filename = filename.substring(filename.lastIndexOf('\\')+1);
        reader.onload = function(e)
         {
           debugger;      
           $('#blah').attr('src', e.target.result);
           $('#blah').hide();
           $('#blah').fadeIn(500);      
           $('.custom-file-label').text(filename);             
         }
        reader.readAsDataURL(input.files[0]);    
      }
  $(".alert").removeClass("loading").hide();
}

function RecurFadeIn()
{ 
  console.log('ran');
  FadeInAlert("Wait for it...");  
}

function FadeInAlert(text)
{
  $(".alert").show();
  $(".alert").text(text).addClass("loading");  
}

Explanation Of Code:

The readURL() function above is used to read the raw file data and generate a preview of it. The FileReader is the object for reading the file using JS. When the file content is stacked, the image preview is attached to the HTML component using jQuery.

After this, the jQuery change() method triggers the readURL() function when a file is chosen. The readURL() function generated a preview of the chosen file and displays it on the web page.

Upload File To The Server Using PHP

image upload jquery source code

You can send the image file to the database server to store your image file once it’s uploaded. You can transfer files to the server using PHP.

First, you need to fetch the file information using $_FILES in PHP, then use move_uploaded_file() function to upload your file. Just follow the code below:

<?php 
$uploadPath = 'uploads/'; 
if(isset($_POST['submit']) && !empty($_FILES['file']['name']))
{ 
    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath.$_FILES['file']['name']))
        { 
          echo 'File has been uploaded successfully.'; 
        }
    else
        { 
          echo 'File upload failed, please try again.'; 
        }
}
?>

Now, the only thing left is to finally test it. We hope you liked our guide to create Image Upload With Preview Using jQuery and CSSCustom File Input Image program.

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here