Simple Image Preview Before Upload

In this tutorial we will show you how to create a Simple Image Preview Before Upload. This feature lets the user view the chosen image before they upload it. And you can easily add image preview option on file upload using JavaScript and jQuery. Simple Image Preview Before Upload is a most required feature for file upload functionality. It helps the user to view chosen file and change the image before upload. From the user perspective, it is very helpful to uploading perfect image or file without doing the repetitive upload.

Sample Code

Upload.php - This script is use to upload the file to the respective directory when the user clicked on submit button.
  1. <?php
  2. if(isset($_POST['submit']) && !empty($_FILES['file']['name'])){
  3. if(move_uploaded_file($_FILES['file']['tmp_name'],"uploads/".$_FILES['file']['name'])){
  4. echo 'File has uploaded successfully.';
  5. }else{
  6. echo 'Some problem occurred, please try again.';
  7. }
  8. }
  9. ?>
JavaScript File Reader - it will be used to read the content of the file in file preview function. Once the file content is loaded we’ll render the image preview under the file upload form.
  1. function filePreview(input) {
  2. if (input.files && input.files[0]) {
  3. var reader = new FileReader();
  4. reader.onload = function (e) {
  5. $('#uploadForm + img').remove();
  6. $('#uploadForm').after('<img src="'+e.target.result+'" width="450" height="300"/>');
  7. }
  8. reader.readAsDataURL(input.files[0]);
  9. }
  10. }
  11. $("#file").change(function () {
  12. filePreview(this);
  13. });
Index.html - This is for the GUI of the web page to make it more responsive and attractive.
  1. <!DOCTYPE html>
  2. <title>Simple Image Preview Before Upload</title>
  3. <link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
  4. <link rel="stylesheet" type="text/css" media="screen" href="bootstrap/css/bootstrap.min.css" />
  5. <script src="js/jquery.min.js"></script>
  6. </head>
  7. <nav class="navbar navbar-default">
  8. <div class="container-fluid">
  9. <div class="navbar-header">
  10. <a class="navbar-brand" href="#"><b>Image Preview Before Upload</b></a>
  11. </div>
  12. </nav>
  13. <div class="container-fluid">
  14. <form method="post" action="upload.php" enctype="multipart/form-data" id="uploadForm">
  15. <div class="button">
  16. <input type="file" name="file" id="file" />
  17. <input type="submit" class="btn btn-default" name="submit" value="Upload" style="margin-left: 385px;margin-top: -25px;"/>
  18. </div>
  19. </form>
  20. </div>
  21. </body>
  22. </html>
Hope that you learn in my tutorial. Don't forget to LIKE & SHARE this website. Enjoy Coding.

Add new comment