Home > PHP > Image upload & preview without page refresh

Image upload & preview without page refresh

File upload without refresh:

If you want to have preview option while selecting the file from your local machine, The below two scripts will helps to achieve your requirement. You can find the form in “index.html” file. When you selects any file it will call JS function “ajaxFileUpload”. Inside of this function we have set form target to iframe.

upload-picture.php acts as a action page. You can see the uploading stuff over there. You can also find the virus scanning(clamscan) in this file.


File 1: index.html

<script>
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<div><img src="images/progressbar.gif" border="0" /></div>';
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
</script>

<!-- iframe used for ajax file upload-->
<!-- debug: change it to style="display:block" -->
<iframe name="upload_iframe" id="upload_iframe" style="display:none;"></iframe>
<!-- iframe used for ajax file upload-->

<form name="pictureForm" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<span>Upload Picture :</span>
<input type="file" name="picture" id="picture" onchange="return ajaxFileUpload(this);" />
<span id="picture_error"></span>
<div id="picture_preview"></div>
</div>
</form>

File 2: upload-picture.php

<?php
$upload_dir = '/var/www/file-upload/upload/'; // Directory for file storing
$preview_url = 'http://localhost/file-upload/upload/';
$filename= '';
$result = 'ERROR';
$result_msg = '';
$allowed_image = array ('image/gif', 'image/jpeg', 'image/jpg', 'image/pjpeg','image/png');
define('PICTURE_SIZE_ALLOWED', 2242880); // bytes

if (isset($_FILES['picture']))  // file was send from browser
{
 if ($_FILES['picture']['error'] == UPLOAD_ERR_OK)  // no error
 {
 if (in_array($_FILES['picture']['type'], $allowed_image)) {
 if(filesize($_FILES['picture']['tmp_name']) <= PICTURE_SIZE_ALLOWED) // bytes
 {
 $filename = $_FILES['picture']['name'];
 move_uploaded_file($_FILES['picture']['tmp_name'], $upload_dir.$filename);

//phpclamav clamscan for scanning viruses
//passthru('clamscan -d /var/lib/clamav --no-summary '.$upload_dir.$filename, $virus_msg); //scan virus
$virus_msg = 'OK'; //assume clamav returing OK.
if ($virus_msg != 'OK') {
unlink($upload_dir.$filename);
$result_msg = $filename." : ".FILE_VIRUS_AFFECTED;
$result_msg = '<font color=red>'.$result_msg.'</font>';
$filename = '';
}else {
// main action -- move uploaded file to $upload_dir
$result = 'OK';
}
}else {
$filesize = filesize($_FILES['picture']['tmp_name']);// or $_FILES['picture']['size']
$filetype = $_FILES['picture']['type'];
$result_msg = PICTURE_SIZE;
}
}else {
$result_msg = SELECT_IMAGE;
}
}
elseif ($_FILES['picture']['error'] == UPLOAD_ERR_INI_SIZE)
$result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
else
$result_msg = 'Unknown error';
}

// This is a PHP code outputing Javascript code.
echo '<script language="JavaScript" type="text/javascript">'."\n";
echo 'var parDoc = window.parent.document;';
if ($result == 'OK') {
echo 'parDoc.getElementById("picture_error").innerHTML =  "";';
}
else {
echo "parDoc.getElementById('picture_error').innerHTML = '".$result_msg."';";
}

if($filename != '') {
echo "parDoc.getElementById('picture_preview').innerHTML = '<img src=\'$preview_url$filename\' id=\'preview_picture_tag\' name=\'preview_picture_tag\' />';";
}

echo "\n".'</script>';
exit(); // do not go futher

?>

Note:
1. Make sure that the upload directory having the permission.
2. To debug, you need to change the style=”display:block” in iframe tag.

Categories: PHP
  1. nabil1984
    August 13, 2009 at 6:53 AM

    Nice method, thanks for sharing.
    You PHP code includes an antivirus scan which is only not widely available.

    • chipstset
      February 21, 2012 at 7:29 AM

      nabil1984 :
      Nice method, thanks for sharing.
      You PHP code includes an antivirus scan which is only not widely available.

  2. Stefan
    September 23, 2009 at 4:12 PM

    Hi,

    Am trying to test your script to see if I can addapt it for my needs.
    The code is not working for me??? If I run it in FF I got the following error code :
    Error: document.getElementById(“picture_preview”) is null

    So i added the “” after the “”

    Now I am only getting the form to echo “SELECT_IMAGE” after selection of a small jpg file….

    What am I doing wrong??? Please help.

    My code in my testaup.php (Your index.html)

    Image Upload and Preview without Page Refresh TEST

    function ajaxFileUpload(upload_field)
    {
    // Checking file type
    var re_text = /\.jpg|\.gif|\.jpeg/i;
    var filename = upload_field.value;
    if (filename.search(re_text) == -1) {
    alert(“File should be either jpg or gif or jpeg”);
    upload_field.form.reset();
    return false;
    }
    document.getElementById(‘picture_preview’).innerHTML = ”;
    upload_field.form.action = ‘ajaxupload.php’;
    upload_field.form.target = ‘upload_iframe’;
    upload_field.form.submit();
    upload_field.form.action = ”;
    upload_field.form.target = ”;
    return true;
    }

    Upload Picture :

    And then my ajaxupload.php (Your upload-picture.php)
    <?php
    $upload_dir = '../ad_images/ajax/'; // Directory for file storing
    $preview_url = '../ad_images/ajax/';
    $filename= '';
    $result = 'ERROR';
    $result_msg = '';

    if (isset($_FILES['picture'])) // file was send from browser
    {
    if ($_FILES['picture']['error'] == UPLOAD_ERR_OK) // no error
    {
    if (in_array($_FILES['picture']['type'], $allowed_image)) {
    if(filesize($_FILES['picture']['tmp_name']) <= PICTURE_SIZE_ALLOWED) // bytes
    {
    move_uploaded_file($_FILES['picture']['tmp_name'], $upload_dir.$filename);
    passthru('clamscan -d /var/lib/clamav –no-summary '.$upload_dir.$filename, $virus_msg); //through phpclamav for scanning viruses
    if ($virus_msg != 'OK') {
    unlink($upload_dir.$filename);
    $result_msg = $filename." : ".FILE_VIRUS_AFFECTED;
    $result_msg = '’.$result_msg.”;
    $filename = ”;
    }else {
    // main action — move uploaded file to $upload_dir
    $result = ‘OK’;
    }
    }else {
    $filesize = filesize($_FILES[‘picture’][‘tmp_name’]);// or $_FILES[‘picture’][‘size’]
    $filetype = $_FILES[‘picture’][‘type’];
    $result_msg = PICTURE_SIZE;
    }
    }else {
    $result_msg = SELECT_IMAGE;
    }
    }
    elseif ($_FILES[‘picture’][‘error’] == UPLOAD_ERR_INI_SIZE)
    $result_msg = ‘The uploaded file exceeds the upload_max_filesize directive in php.ini’;
    else
    $result_msg = ‘Unknown error’;
    }

    // This is a PHP code outputing Javascript code.
    echo ”.”\n”;
    echo ‘var parDoc = window.parent.document;’;
    if ($result == ‘OK’) {
    echo ‘parDoc.getElementById(“picture_error”).innerHTML = “”;’;
    }
    else {
    echo “parDoc.getElementById(‘picture_error’).innerHTML = ‘”.$result_msg.”‘;”;
    }

    if($filename != ”) {
    echo “parDoc.getElementById(‘picture_preview’).innerHTML = ”;”;
    }

    echo “\n”.”;
    exit(); // do not go futher

    ?>

    • Anonymous
      July 27, 2012 at 3:42 PM

      It’s working and image privew properly . so, How to insert file in database.Becase am trying $filename = $_FILES[‘picture’][‘name’]; to print_r() not print any value.

      Thanks…

    • debashish jena
      July 27, 2012 at 3:45 PM

      i am create image upload plugin in local host for my site..
      It’s working and image privew properly . so, How to insert file in database.Becase am trying $filename = $_FILES[‘picture’][‘name’]; to print_r() not print any value.

      Thanks…

  3. Stefan
    September 23, 2009 at 9:51 PM

    Ok, got it all working… Thanks (This if anybody will ever read my message or question???)
    What function should I use if I want the uploaded image deleted without refresh?

    Thanks….

    • Anonymous
      November 8, 2009 at 9:15 PM

      Hey… I am getting the same error? What was/is the problem. Any help will be appreciated.

  4. Warren
    November 8, 2009 at 9:16 PM

    Hey… I am getting the same error? What was/is the problem. Any help will be appreciated.

  5. November 18, 2009 at 11:24 AM

    Warren we updated the new script. please use it.

    • Ira
      December 13, 2009 at 10:57 PM

      I’m having trouble getting this to work. What do I need to change in the index.htm and the upload-picture.php ? In The upload-picture.php I’ve changed the $upload_dir and $preview_url, however; I’m not entirely sure what to change them to. I’ve changed the $upload_dir to: http://localhost/www.BLANK.com/ (“BLANK” is my site). I changed $preview_url to the same thing. Could you give me a more detailed explanation on how and why I’m changing these.

  6. February 21, 2010 at 4:49 PM

    like it very much,.. thanks for sharing..

  7. JC from France
    April 23, 2010 at 1:15 PM

    Nice Tutorial, excuse me for bad english … I made a upload form for a classifieds site and your method is very good compare to some flash or flex uploader (to complecated and need Flash CS4 ) and it’s a good alternative ! There are a lot of ‘JS preview before upload’ ON THE WWW but there aren’t working. I tested your script with WAMP / LAMP it works great THANKS !

  8. moch
    April 30, 2010 at 8:39 AM

    The code does not work for me. There’s no error but I can’t see images in upload directory and image doesn’t preview. Sorry for bad english.
    Note: I did not change anything and I also have the upload folder.

  9. ayodeji
    May 8, 2010 at 7:54 PM

    how do i preview an uploaded image or picture before submit using php

  10. September 19, 2010 at 12:38 AM
  11. September 19, 2010 at 12:50 AM
  12. Raj
    November 18, 2010 at 6:53 PM

    thanks for the code…bt it seems like having some small pblm in this code….y bcoz…its nt showing some images which is browsed from anyother drive like eg; c,d,etc..need 2 check in that it seems…

  13. December 7, 2010 at 12:16 PM

    I like that your validation for filetype and size is written in the simplest form possible. You should write a separate post for that simply because the only ones available aren’t half as good. cheers

  14. zhandos
    December 28, 2010 at 11:29 PM

    Its working perfect. very appreciate

  15. Hatrick
    May 8, 2011 at 3:05 PM

    Thanks. It worked.. but i want to put the image into database. how could i do that?

    • husenEF
      May 28, 2011 at 8:39 AM

      ihave form:
      <for
      <input type="hidden" name="id_user" value="” />

      <a href="#" title="""” class=”vtip”>

      produkt:

      <a href="#" title="""” class=”vtip”>

       Du har gemt ud af

       

       

        mulige

      <a href="#" title="""” class=”vtip”>

      producent:

      <a href="#" title="""” class=”vtip”>

      model:

       

       

      <a href="#" title="""” class=”vtip”>

      imei/stel/serienummer
       
       

       

      <input name="serial_number" type="text" id="serial_number" class="" value="”/>

       

      Imeinr
      Stelnr
      Serienr

      <!– Stjålet
      Tabt
      Solgt–>

      <a href="index.php?page=generator&id_user=” target=”_blank” >Generér serienummer

      <a href="#" title="""” class=”vtip”>

      købs dato

      <a href="#" title="""” class=”vtip”>

      købs lokation

       

       

      <?php /*
      Din e-mail adresse

       

      */ ?>

      <a href="#" title="""” class=”vtip”>

      <!– upload fil(tilladte filtyper jpeg, jpg, bmp, gif og png.Max.filstørrelse 5 MB):*–>
      upload photo

       

      #picture_preview{
      float: right;
      margin-right: 49px;
      }
      #picture_preview img{
      max-width: 100px;
      }

      <!– –>

      <?php /*

      (function() {
      var demo = new ImageUploadPreview(

      // Upload Input Element
      document.getElementById(‘upload’),

      // onPreviewSuccess handler.
      function(imgInfo) {
      var info = [];
      for (var i in imgInfo) {
      info.push(”, i, ‘ = ‘, imgInfo[i], ”);
      }

      if (info.length) {
      info.unshift(”);
      info.push(”);
      }
      this.getImageElement().className = ‘preview-image’;
      document.getElementById(‘file-info’).innerHTML = info.join(”);
      },

      // onPreviewFail handler.
      function() {
      this.getImageElement().className = ”;
      });

      demo.setMaxImageSize(demo.getInputElement().offsetWidth, 50);

      // If the value already exists, try display image.
      demo.preview();
      })();
      */?>

       
      <!– upload fil(tilladte filtyper jpeg, jpg, bmp, gif og png.Max.filstørrelse 5 MB):*–>
      upload photo

       

      (function() {
      var demo = new ImageUploadPreview(

      // Upload Input Element
      document.getElementById(‘upload2’),

      // onPreviewSuccess handler.
      function(imgInfo) {
      var info = [];
      for (var i in imgInfo) {
      info.push(”, i, ‘ = ‘, imgInfo[i], ”);
      }

      if (info.length) {
      info.unshift(”);
      info.push(”);
      }
      this.getImageElement().className = ‘preview-image2’;
      document.getElementById(‘file-info’).innerHTML = info.join(”);
      },

      // onPreviewFail handler.
      function() {
      this.getImageElement().className = ”;
      });

      demo.setMaxImageSize(demo.getInputElement().offsetWidth, 50);

      // If the value already exists, try display image.
      demo.preview();
      })();

       
      upload fil(tilladte filtyper jpeg, jpg, bmp, gif og png.Max.filstørrelse 5 MB):*

       

      (function() {
      var demo = new ImageUploadPreview(

      // Upload Input Element
      document.getElementById(‘upload3’),

      // onPreviewSuccess handler.
      function(imgInfo) {
      var info = [];
      for (var i in imgInfo) {
      info.push(”, i, ‘ = ‘, imgInfo[i], ”);
      }

      if (info.length) {
      info.unshift(”);
      info.push(”);
      }
      this.getImageElement().className = ‘preview-image3’;
      document.getElementById(‘file-info’).innerHTML = info.join(”);
      },

      // onPreviewFail handler.
      function() {
      this.getImageElement().className = ”;
      });

      demo.setMaxImageSize(demo.getInputElement().offsetWidth, 50);

      // If the value already exists, try display image.
      demo.preview();
      })();

       
      upload fil(tilladte filtyper jpeg, jpg, bmp, gif og png.Max.filstørrelse 5 MB):*

       

      (function() {
      var demo = new ImageUploadPreview(

      // Upload Input Element
      document.getElementById(‘upload4’),

      // onPreviewSuccess handler.
      function(imgInfo) {
      var info = [];
      for (var i in imgInfo) {
      info.push(”, i, ‘ = ‘, imgInfo[i], ”);
      }

      if (info.length) {
      info.unshift(”);
      info.push(”);
      }
      this.getImageElement().className = ‘preview-image4’;
      document.getElementById(‘file-info’).innerHTML = info.join(”);
      },

      // onPreviewFail handler.
      function() {
      this.getImageElement().className = ”;
      });

      demo.setMaxImageSize(demo.getInputElement().offsetWidth, 50);

      // If the value already exists, try display image.
      demo.preview();
      })();

       
      upload fil(tilladte filtyper jpeg, jpg, bmp, gif og png.Max.filstørrelse 5 MB):*

       

      (function() {
      var demo = new ImageUploadPreview(

      // Upload Input Element
      document.getElementById(‘upload5’),

      // onPreviewSuccess handler.
      function(imgInfo) {
      var info = [];
      for (var i in imgInfo) {
      info.push(”, i, ‘ = ‘, imgInfo[i], ”);
      }

      if (info.length) {
      info.unshift(”);
      info.push(”);
      }
      this.getImageElement().className = ‘preview-image5’;
      document.getElementById(‘file-info’).innerHTML = info.join(”);
      },

      // onPreviewFail handler.
      function() {
      this.getImageElement().className = ”;
      });

      demo.setMaxImageSize(demo.getInputElement().offsetWidth, 50);

      // If the value already exists, try display image.
      demo.preview();
      })();

      <a href="#" title="""” class=”vtip2″>

      Beskrivelse af produktet:

       

       
      Status

       

      Stjålet
      Tabt
      Solgt
      Stadig i ejers varetægt

       
      <?php if ($pRow

      but, if click submit. action not working….

  16. Anonymous
    July 10, 2011 at 10:44 AM

    Stefan :
    Ok, got it all working… Thanks (This if anybody will ever read my message or question???)
    What function should I use if I want the uploaded image deleted without refresh?
    Thanks….

  17. August 22, 2011 at 6:48 PM

    Very nice and useful piece of code…
    Thanks to that person who uploaded this…
    Really Thanks

  18. February 3, 2012 at 3:24 AM

    Wow, thank you so much! This was what i was looking for!

  19. February 8, 2012 at 2:37 AM

    thanks very much…
    you help me to finish my final project….
    God bless you

  20. Vikas Uniyal
    February 9, 2012 at 4:45 PM

    Its nice but how to manage the size of image to show?

  21. April 3, 2012 at 1:03 PM

    Thank you

  22. Thankful
    May 1, 2012 at 7:26 PM

    this works, thank you very much. I need it to do more, but this really helped me tons. thx

  23. October 10, 2012 at 4:05 PM

    Is there an option to preview the image as base64 instead of storing it on the server?
    Maybe with file_put_contents($image, base64_decode($str));

  24. December 26, 2012 at 8:01 PM

    Hi there! Someone in my Facebook group shared this site with us so I came
    to look it over. I’m definitely enjoying the information. I’m bookmarking
    and will be tweeting this to my followers! Superb blog and fantastic design and style.

  25. May 7, 2013 at 1:51 PM

    you’re in reality a good webmaster. The web site loading speed is incredible. It seems that you are doing any unique trick. In addition, The contents are masterwork. you have done a wonderful activity on this subject!

  26. June 11, 2013 at 8:31 AM

    Amazing issues here. I’m very glad to look your post. Thanks so much and I am taking a look forward to contact you. Will you kindly drop me a e-mail?

  27. August 15, 2013 at 10:08 AM

    Or The Very Hungry Caterpillar.

  28. Anonymous
    November 7, 2013 at 3:53 PM

    Thanks.. its nioce………..

  29. October 11, 2015 at 8:48 AM

    Thanks for some other excellent post. Where else may anyone get that type of
    information in such an ideal means of writing? I’ve a presentation next week, and
    I’m on the search for such info.

  30. August 7, 2017 at 8:31 AM

    Great post.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: