Upload image by selecting it and showing thumbnail without refresh on page

9

How do I make a code to send an image when I select it during registration? And after sending a thumbnail appears on the form, then the user will continue filling in the rest of the form.

Similar to what is done in this link .

    
asked by anonymous 13.02.2014 / 10:49

2 answers

14

In order to be able to upload an image to the server and after submitting it successfully, you need to make use of Ajax and preferably a plugIn that already takes care of all the work of interacting with the server.

Code

The essential code for creating an HTML form and a file on the server side is to deal with the arrival of the files and to control the files minimally:

HTML

This file will be index.php where we have the HTML required to submit a form to the visitor, as well as include jQuery and the jQuery Form Plugin modified by Arun Sekar .

<!doctype html>
<html>
<head>
  <title>Ajax Image Upload </title>

  <style type="text/css">
    body {
      font-family:sans-serif;
    }
    #preview {
      color:#cc0000;
      font-size:12px
    }
    .imgList {
      max-height:150px;
      margin-left:5px;
      border:1px solid #dedede;
      padding:4px;
      float:left;
    }
  </style>

  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript" src="js/jquery.wallform.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {

      $('#photoimg').die('click').live('change', function() {

        $("#imageform").ajaxForm({
          target: '#preview',
          beforeSubmit: function(){
            console.log('Antes de enviar');
            $("#imageloadstatus").show();
            $("#imageloadbutton").hide();
          },
          success:function(){
            console.log('Envio com sucesso');
            $("#imageloadstatus").hide();
            $("#imageloadbutton").show();
          },
          error:function(){
            console.log('Erro ao realizar operação');
            $("#imageloadstatus").hide();
            $("#imageloadbutton").show();
          }
        }).submit();
      });
    });
  </script>
</head>
<body>
  <div>
    <div id='preview'></div>
    <form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
      <h1>Escolha as imagens a carregar</h1>
      <div id='imageloadstatus' style='display:none'>
        <img src="loader.gif" alt="A carregar....">
      </div>
      <div id='imageloadbutton'>
        <input type="file" name="photos[]" id="photoimg" multiple="true">
      </div>
    </form>
  </div>
</body>
</html>

PHP

This file will be the ajaxImageUpload.php with which the jQuery plugin will interact to send the photo data and receive information if it was uploaded successfully to the server, so that submit the same to the visitor without the refresh of the page.

<?php
error_reporting(0);
session_start();

define("MAX_SIZE","9000");

function getExtension($str) {

    $i = strrpos($str,".");

    if (!$i) {
        return "";
    }

    $l = strlen($str) - $i;

    $ext = substr($str,$i+1,$l);

    return $ext;
}

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");

if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {

    $uploaddir = "uploads/"; // directoria que vai receber os ficheiros

    foreach ($_FILES['photos']['name'] as $name => $value) {

        $filename = stripslashes($_FILES['photos']['name'][$name]);

        $size=filesize($_FILES['photos']['tmp_name'][$name]);

        /* Recolhe extensão do ficheiro em caixa baixa (lowercase)
         */
        $ext = getExtension($filename);
        $ext = strtolower($ext);

        if (in_array($ext,$valid_formats)) {

            if ($size < (MAX_SIZE*1024)) {

                $image_name=time().$filename;

                $newname=$uploaddir.$image_name;

                if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {
                    /* ficheiro carregado com sucesso,
                     * envia HTML com imagem para apresentar ao visitante
                     */
                    echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
                } else {
                    echo '<span class="imgList">Ficheiro não foi carregado!</span>';
                }
            } else {
                echo '<span class="imgList">Limite de tamanho atingido!</span>';
            }
        } else {
            echo '<span class="imgList">Extensão do ficheiro desconhecida!</span>';
        }
    }
}

?>

Result

The result of using the code above is what can be seen in this animated GIF with 4 steps:

  • Form;
  • Image to be sent to the server;
  • Image to be displayed;
  • Second image to display.

Download

YoucandownloadallthenecessaryfilesfrommyDropBox:

Link to multiple_upload.zip file .

Explanation

In order to better understand what is happening, it follows a superficial explanation giving information relevant to an understanding of the whole process:

  • The jQuery plugin will be aware of the form so that when the user chooses a file, an action will be triggered that will send the same to the server

  • On the server side, we are verifying / validating the incoming file and respond to the jQuery plugin by sending the HTML that we want it to apply to the page. When everything runs as we want, the submitted HTML is TAG img with path to the image.

  • The jQuery plugin then receives the HTML, presents the same and unlocks the ace

  • Credits for this solution for the web-site www.9lessons. info: Ajax Select and Upload Multiple Images with Jquery

        
    13.02.2014 / 12:48
    2

    To simply display the image on the screen at the time of choice, simply implement the js code below:

    $("##ID DO INPUT FILE##").change(function (event) {
        var reader = new FileReader();
        $(reader).load(function (event) {
            $("##ID DO ELEMENTO IMG##").attr("src", event.target.result);
        });
        reader.readAsDataURL(event.target.files[0]);
    });
    
        
    25.02.2014 / 22:24