Preview Image before Upload using jQuery

Preview image feature lets the user view the chosen image before upload. Preview image 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.

You can easily add image preview option on file upload using JavaScript and jQuery. In this tutorial, we’ll write some JavaScript and jQuery code to preview image before upload. Also, we’ll provide the way to preview any types of files before file upload. Follow our example script with instruction on preview image before upload using jQuery.


The example script uses some jQuery with JavaScript so at first include the jQuery library.

<script src="jquery.min.js"></script>

JavaScript FileReader will be used to read the content of the file in filePreview() function. Once the file content is loaded we’ll render the image preview under the file upload form.

function filePreview(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#uploadForm + img').remove();
            $('#uploadForm').after('<img src="''" width="450" height="300"/>');

If you want to preview all type of file, use <embed> tag instead of <img> tag. Place the following code in the reader.onload event and remove the existing code.

$('#uploadForm + embed').remove();
$('#uploadForm').after('<embed src="''" width="450" height="300">');

Now call the filePreview() method on change the file input.

$("#file").change(function () {

Place this complete JavaScript code after the Form HTML.


Simple HTML form with file input and submit button.

<form method="post" action="upload.php" enctype="multipart/form-data" id="uploadForm">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Upload"/>

Upload File using PHP

Use simple PHP code to upload the file to the respective directory when the user clicked on submit button.

if(isset($_POST['submit']) && !empty($_FILES['file']['name'])){
'File has uploaded successfully.';
'Some problem occurred, please try again.';

1 Comment

  1. Gustavo Said...

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.