Preview more than one image before upload

Asked

Viewed 3,952 times

0

hello folks I’m developing a real estate site, but I’m still a little layy in php, a friend of mine was helping me , but now he can no longer, is the following the system I want is the following, Let’s say that in my database I have several registered properties and I need to change only the photos of the property and still see the photos I will send to the database and folder before I upload the image. You know like the facebook site when we edit the profile image for example and it shows us the right loaded image. How do I do this.

Note: I want to do the multiple preview, ie preview more than one photo.

<?php
session_start();
if (isset($_SESSION['usuario'])&&isset($_SESSION['logado'])) {
/*
paginas que adiciona fotos no imóvel
*/


 //verifico se foi passado o ID do imóvel
 if (!isset($_GET['id'])):


//Caso não voltar a pagina
echo '<div class="erro">Operação incorreta</div>';
header('Refresh: 1; ?pag=imoveis_fotos');


else:
$imv_id = $_GET['id'];


 endif;

 //verifico a quantidade de fotos que existe no imovel

  $fotos = new Conexao();
  $fotos->ExecSQL("select * from imoveis_fotos where foto_imovel =     

   '$imv_id'");


   //tratando o limite de fotos
    $limite = (Sistema::getLimiteFotos() - $fotos->TotalRegistros());
    ?>

     <!--Scripts da biblioteca de upload de imagens-->
     <script src="../lightbox/js/jquery-1.11.0.min.js"></script>
     <script src="uploadify/jquery.uploadify.min.js"          
      type="text/javascript"></script>
       <link rel="stylesheet" type="text/css"   
       href="uploadify/uploadify.css">


      <div class="texto"> 
       <p id="quem" style="margin-bottom:40px;">Adicionar imagens
       </p>
       <?php
       echo '<center><div style="border:1px solid #000; width:500px;    
       margin-bottom:50px; font-weight:bolder;">Este imóvel tem ' .  
       $fotos->TotalRegistros() . ' imagens, o limite é ' .  
       Sistema::getLimiteFotos() . '.<br>Você pode enviar ainda: ' .  
        $limite . ' imagem(s)</div></center>';

         if($limite < 1):
         die('<div id="erro">O limite de imagem deste imóvel esgotou.       
         Caso queira outras imagens precisa apagar algumas.</div>');
          endif;


           ?>
           <script src="uploadify/jquery.uploadify.min.js"  
           type="text/javascript"></script>
           <link rel="stylesheet" type="text/css"  
            href="uploadify/uploadify.css">


            <center>   <form>
            <div id="queue"></div>
            <input id="file_upload" name="file_upload" type="file"     
             multiple="true">
             </form>

              <script type="text/javascript">
              <?php $timestamp = time();?>
               $(function() {
               $('#file_upload').uploadify({
               'formData'     : {
                                    'imovel': '<?php echo $imv_id ;?>', 
                'timestamp' : '<?php echo $timestamp;?>',
                'token'     : '<?php echo md5('unique_salt' .  
                 $timestamp);?>'
                  },
                  'swf'      : 'uploadify/uploadify.swf',
                   'uploader' : 'uploadify/uploadify.php',
                            'buttonText': 'Selecionar arquivo',
                            'uploadLimit': <?php echo $limite ?>,


                            // depois de terminar
                             'onQueueComplete' : function(queueData) {
                        alert(queueData.uploadsSuccessful + ' Imagem (ns)  
                        foram carregadas.');
                        url = '?pag=imoveis_fotos&id=<?php echo $imv_id  
                         ;?>';
                         $(location).attr("href",url);

                           } // fim do onQueueComplete
                            });
                                });





                              </script>
                              </center>


                               </div>
                               <a style="background: #73c425;                 
                                font-family:'OpenSans', sans-serif;  
                                  padding: 5px;  margin-left: 10px; 
                                  font-size: 15px; text-transform:none;" 
                                  href="?pag=imoveis_fotos&id=<?php echo  
                                  $imv_id; ?>">Voltar</a>





                                   <?php } else  
                                   {header("Location:login.php");} ?>

4 answers

0

To preview/as/s before upload

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
  .imageThumb {
     max-height: 75px;
     border: none;
     margin: 10px 10px 0 0;
     padding: 1px;
  }
</style>
<script>

$(function() {
    // Multiple images preview in browser
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img class="imageThumb">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }

    };

    $('#gallery-photo-add').on('change', function() {
        imagesPreview(this, 'div.gallery');
    });
});

</script>

 <form action="upload_fotos.php" method="post" enctype="multipart/form-data">
  <input type="file" name="files[]" multiple id="gallery-photo-add">
  <input type="submit" name='submit_image' value="Upload Image"/>
 </form>
 <div class="gallery"></div>

upload_photos.php

<style>
      .imageThumb {
         max-height: 75px;
         border: none;
         margin: 10px 10px 0 0;
         padding: 1px;
      }
</style>

<?php

if(is_array($_FILES))
{
    $output = '';


    foreach ($_FILES['files']['name'] as $name => $value)
    {
        $values .= "('{$value}'),";

                //com mais colunas ex:
                //$values .= " (NULL, '{$id_recuperado}', '{$nome}'),";


            $diretorio = "foto/".$value;

            if(move_uploaded_file($_FILES['files']['tmp_name'][$name], $diretorio))
            {
                $output .= '<img src="'.$diretorio.'" class="imageThumb" />';
            }
    }
    echo "imagens processadas <br>".$output;

    $values=substr($values, 0, -1);

    //conexão
    //$conn=.....

    $sql_fotos = "INSERT INTO `imoveis_fotos` (`nomeColuna`) VALUES $values";

            //com mais colunas ex:
            //$sql_fotos = "INSERT INTO `imoveis_fotos` (`id`, `id_imagem`, `arquivo`) VALUES $values";

    $result = mysqli_query($conn,$sql_fotos);

}


?>

0

Here are some tips to preview 1 image ;)

In HTML you will have something like this:

<form id="form1" >
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="descricao imagem blablal" />
</form>

In Javascript:

function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

What this code will do is read the submitted file and present before performing any action like Upload. Of course you will have to adapt but the function that does what you want is the readUrl() that sending the input there will render the image to the screen.

  • Thanks, but this code is only to view one image at a time?

  • You will have to adapt using Arrays :)

0

$(function() {
// Pré-visualização de várias imagens no navegador
var visualizacaoImagens = function(input, lugarParaInserirVisualizacaoDeImagem) {

    if (input.files) {
        var quantImagens = input.files.length;

        for (i = 0; i < quantImagens; i++) {
            var reader = new FileReader();

            reader.onload = function(event) {
                $($.parseHTML('<img class="miniatura">')).attr('src', event.target.result).appendTo(lugarParaInserirVisualizacaoDeImagem);
            }

            reader.readAsDataURL(input.files[i]);
        }
    }

};

$('#addFotoGaleria').on('change', function() {
    visualizacaoImagens(this, 'div.galeria');
});
});
  .miniatura {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" multiple id="addFotoGaleria">
<div class="galeria"></div>

0

$(function() {
    // Pré-visualização de várias imagens no navegador
    var visualizacaoImagens = function(input, lugarParaInserirVisualizacaoDeImagem) {    
        if (input.files) {
            var quantImagens = input.files.length;

            for (i = 0; i < quantImagens; i++) {
                var reader = new FileReader();

                reader.onload = function(event) {
                    $($.parseHTML('<img class="miniatura">')).attr('src', event.target.result).appendTo(lugarParaInserirVisualizacaoDeImagem);
                }

                reader.readAsDataURL(input.files[i]);
            }
        }    
    };

    $('#addFotoGaleria').on('change', function() {
        visualizacaoImagens(this, 'div.galeria');
    });
});
.miniatura {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" multiple id="addFotoGaleria">
<div class="galeria"></div>

How do I make it so that when loading new photos the old ones come out of the preview?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.