How to Make Bootstrap Modal with File Upload and Preview – jQuery AJAX

Bootstrap Modal is a popup container which use to show various types of information on the screen.

It is very flexible and user-friendly.

You can display a new entry or update form in it.

In this tutorial, I am using Bootstrap Modal for image file upload and display preview using jQuery and AJAX.

How to Make Bootstrap Modal with File Upload and Preview - jQuery AJAX


Contents

  1. HTML
  2. PHP
  3. jQuery
  4. Conclusion

1. HTML

Create a button and Bootstrap Modal.

In the Bootstrap Modal create a file element in the <form> and for display image preview after upload created a <div id='preview'>.

Completed Code

<button type="button" class="btn btn-info" data-toggle="modal" data-target="#uploadModal">Upload file</button>

<!-- Modal -->
<div id="uploadModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">File upload form</h4>
      </div>
      <div class="modal-body">
        <!-- Form -->
        <form method='post' action='' enctype="multipart/form-data">
          Select file : <input type='file' name='file' id='file' class='form-control' ><br>
          <input type='button' class='btn btn-info' value='Upload' id='btn_upload'>
        </form>

        <!-- Preview-->
        <div id='preview'></div>
      </div>
 
    </div>

  </div>
</div>

2. PHP

Create a ajaxfile.php file and upload folder for storing files.

Define valid image extensions in an $image_ext Array variable.

Select file extension and check it in $image_ext.

If a file has a valid extension then store the selected file to upload folder and return file path.

Completed Code

<?php

// file name
$filename = $_FILES['file']['name'];

// Location
$location = 'upload/'.$filename;

// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);

// Valid image extensions
$image_ext = array("jpg","png","jpeg","gif");

$response = 0;
if(in_array($file_extension,$image_ext)){
    // Upload file
    if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
        $response = $location;
    }
}

echo $response;

3. jQuery

On the upload button click select the browsed file and create a FormData object for passing file data in AJAX request.

When AJAX request successfully callback then check its response.

If the response is 0 means file is not uploaded otherwise display image preview by creating a <img> element in the <div id='preview'> and use response value to set the image source.

Completed Code

$(document).ready(function(){
  $('#btn_upload').click(function(){

    var fd = new FormData();
    var files = $('#file')[0].files[0];
    fd.append('file',files);

    // AJAX request
    $.ajax({
      url: 'ajaxfile.php',
      type: 'post',
      data: fd,
      contentType: false,
      processData: false,
      success: function(response){
        if(response != 0){
          // Show image preview
          $('#preview').append("<img src='"+response+"' width='100' height='100' style='display: inline-block;'>");
        }else{
          alert('file not uploaded');
        }
      }
    });
  });
});

4. Conclusion

Within the Bootstrap Modal create your file element in the <form> and use jQuery AJAX for storing file to the server and display preview.

If you found this tutorial helpful then don't forget to share.

13 thoughts on “How to Make Bootstrap Modal with File Upload and Preview – jQuery AJAX”

  1. This is nice. I just finished one using Colorbox. I like this with the Bootstrap modal. I tweaked it a wee bit with some error checking (Empty file, file exists and wrong file type) and some styling. Works pretty good! Thanks.

    Reply
  2. Hi dear Yogesh,
    I have a modal upload issue with a plugin I have purchased from Codecanyon, called Drag & Drop Email Editor Jquery version. Basically the problem is that when I try to upload an image the image is saved into my server, but it doesn’t show up immediately in the modal. It only appear if I clear the browser’s cache. This is a big problem, because each time you need to upload an image, if you have to clear browser cache, then you have to login again, etc… I’s really frustrating.
    I have downloaded and checked the example you shared here. Yours works perfectly fine. Uploaded images are shown in the modal. I wonder if… Is it possible that you help me fix this issue for a fee ? Because I have contacted the plugin author but he’s not really present for support. So I need someone to help me fix this. Please let me know. Thanks 🙂

    Reply
  3. Hi,
    thanks for your interesting post. I’m trying to use it with an improvement that I cannot build: I need to perform a file Upload from different buttons, and I need to choose a different directory depending of the button that has been pressed.
    I tryied to set a value in any button, but the value of the button is not been seen from ajaxload.php, because (I guess) the commit of the form with the buttons is not happened.
    How can I workaround this problem?

    Reply

Leave a Comment