Foros del Web » Programando para Internet » Javascript »

[SOLUCIONADO] Thumbnail a partir de un input type file

Estas en el tema de Thumbnail a partir de un input type file en el foro de Javascript en Foros del Web. No se si lo que quiero hacer se puede, espero poder explicarme bien: Lo que quiero hacer es que el usuario cargue una imagen en ...
  #1 (permalink)  
Antiguo 18/10/2014, 16:07
 
Fecha de Ingreso: septiembre-2008
Mensajes: 66
Antigüedad: 15 años, 7 meses
Puntos: 0
Thumbnail a partir de un input type file

No se si lo que quiero hacer se puede, espero poder explicarme bien:
Lo que quiero hacer es que el usuario cargue una imagen en un input type file y cuando lar cargue, sin recargar la pagina, se genere un thumbnail del archivo que cargó.

No se cómo encarar la función de javascript ni siquieira como buscarlo en google. Alguna idea?
  #2 (permalink)  
Antiguo 18/10/2014, 19:15
Avatar de ArturoGallegos
Moderador
 
Fecha de Ingreso: febrero-2008
Ubicación: Morelia, México
Mensajes: 6.774
Antigüedad: 16 años, 2 meses
Puntos: 1146
Respuesta: Thumbnail a partir de un input type file

puedes buscar en google "upload file with ajax" con eso encontraras como cargar la imagen sin recargar la pagina y por ende tras cargarla conocerás la url para añadirla al contenido que se esta visualizando.
  #3 (permalink)  
Antiguo 18/10/2014, 20:44
 
Fecha de Ingreso: septiembre-2008
Mensajes: 66
Antigüedad: 15 años, 7 meses
Puntos: 0
Respuesta: Thumbnail a partir de un input type file

Muchas gracias por responder. Pero lo solucioné con el framework bootstrap. El cual recomiendo. En la página bootsnip, donde hay un montón e interesantes ejemplos de muchas cosas. Dejo el link por si a alguien le interesa:

http://bootsnipp.com/user/snippets/KG6ag
  #4 (permalink)  
Antiguo 19/10/2014, 08:29
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Thumbnail a partir de un input type file

no es necesario ningún framework.

este código hace más de lo que se trata en este post (si se adjuntan los archivos .php). pero como se trata de mostrar las imágenes seleccionadas sin subirlas, no hay caso

Código:
<!DOCTYPE html>
<html dir="ltr" lang="es-es">
<head>
<title></title>
<meta charset="utf-8">
<style>
* {
    margin: 0;
    padding: 0;
    position: relative;
}


#tmp_imgs {
    list-style: none;
    width: 30%;
    margin: 0 auto;
    padding: 10px 0;
    border: 1px solid rgb(177, 184, 177);
    display: none;
}



#tmp_imgs > li {
    width: 100%;
}



img.thumbnail {
    width: 20%;
    display: inline-block;
    opacity: .4;
    background-color: rgb(255, 255, 255);
    vertical-align: middle;
}


div.barra {
    width: 70%;
    height: 20px;
    display: inline-block;
    margin-left: 5%;
    border: 1px solid rgb(172, 166, 166);
    border-radius: 6px;
    background-color: rgb(201, 49, 104);

}


div.barraProgreso {
    width: 0;
    height: 100%;
    background-color: rgb(118, 196, 47);
    border-radius: 6px;
}


span.porcentaje {
    position: absolute;
    top: 0;
    left: 46%;
    font: bold .8em Verdana;
    color: rgb(255, 255, 255);
}


span.errores {
    float: right;
    right: 5px;
    top: 0;
    position: absolute;
    font: .7em Tahoma;
    color: rgb(201, 49, 104);
}
</style>
<script type="text/javascript">
var uploadFileAjax = new (function() {

    var archivosAsubir = [];
    var cuantos = 0;
    var esteArchivo = null;


    function initSubirImg(evt, frm) {

        if (archivosAsubir.length == 0) return false;

        if (!window.FormData) { // IE

            return true;

        } else {

            evt.preventDefault();

            var errores = {
                'ko1' : 'El tipo de archivo no está permitido. Se admiten (' + frm.archivos.getAttribute('accept') + ')',
                'ko2' : 'El tamaño del archivo supera el máximo permitido'
            }
            var uri = frm.action;
            var ajax = new XMLHttpRequest();
            var fData = new FormData();
            ajax.open('POST', uri, true);
            var i;

            ajax.onreadystatechange = function(){

                if (ajax.readyState == 4 && ajax.status == 200) {

                    var respuesta = JSON.parse(ajax.responseText);

                    var ktal = respuesta.ktal;

                    for (var n = 0; n < ktal.length; n++) {
                      
                      if (ktal[n] == 'ok') {

                        document.querySelectorAll('.barraProgreso')[n].style.width = '100%';
                        document.querySelectorAll('.porcentaje')[n].textContent = '100%';
                        document.querySelectorAll('.thumbnail')[n].style.opacity = 1;

                      } else {

                        document.querySelectorAll('.barraProgreso')[n].style.width = '0%';
                        document.querySelectorAll('.porcentaje')[n].textContent = '0%';
                        document.querySelectorAll('.errores')[n].textContent = errores[ktal[n]];
                      }
                      
                    }
                }
            }


            for (i = cuantos; i < archivosAsubir.length; i++) {

                fData.append('archivo_'+i, archivosAsubir[i]);

                (function(i) {

                    ajax.upload.addEventListener('progress', function(event) {progreso(event, i)}, false);

                })(i);
            }

            cuantos = i;
            ajax.send(fData);
        }
    }



    function progreso(evt, indice) {

        var porcentaje = Math.round((evt.loaded / evt.total) * 100) - 1;

        document.querySelectorAll('.barraProgreso')[indice].style.width = porcentaje + '%';
        document.querySelectorAll('.porcentaje')[indice].textContent = porcentaje + '%';
    }


    function mostrarImg() {

        document.getElementById('archivos').addEventListener('change', function() {

            if (this.files == null || this.files == 'underfined') {

console.log('no acepta la funcionalidad');
                archivosAsubir.push('IE');
                return false;
            }

            if (this.files.length == 0) return false;

            esteArchivo = this.files[0];

            if (this.getAttribute('accept').indexOf(esteArchivo['type']) == -1) {alert('El tipo de archivo no está permitido'); this.value = ''; return false;}

            if (esteArchivo['size'] > 170000) {alert('El tamaño del archivo supera el máximo permitido'); this.value = ''; return false;}

            var lector = new FileReader();

            lector.addEventListener('load', function(event) {

                var fragListado = document.createDocumentFragment();

                var li = document.createElement('li');
                li.setAttribute('class', 'lista');

                var contenido = fragListado.appendChild(li);

                var img = document.createElement('img');
                img.setAttribute('src', event.target.result);
                img.setAttribute('class', 'thumbnail');

                contenido.appendChild(img);

                var barra = document.createElement('div');
                barra.setAttribute('class', 'barra');

                var contenidoBarra = contenido.appendChild(barra);

                var barraProgreso = document.createElement('div');
                barraProgreso.setAttribute('class', 'barraProgreso')

                var porcentaje = document.createElement('span');
                porcentaje.setAttribute('class', 'porcentaje');
                porcentaje.textContent = '0%';

                contenidoBarra.appendChild(barraProgreso);
                contenidoBarra.appendChild(porcentaje);

                var error = document.createElement('span');
                error.setAttribute('class', 'errores');

                contenido.appendChild(error);

                img.addEventListener('load', function() {

                    archivosAsubir.push(esteArchivo);

                    document.getElementById('tmp_imgs').style.display = 'block';
                    document.getElementById('tmp_imgs').appendChild(fragListado);

                }, false);

            }, false);

            lector.readAsDataURL(esteArchivo);

        }, false);
    }

    window.addEventListener('load', mostrarImg, false);

    this.initSendImg = initSubirImg;

})();
</script>
</head>
<body>

    <form action="subirArchivos.php" method="post" name="f" id="f" enctype="multipart/form-data" onSubmit="return uploadFileAjax.initSendImg(event, this)">
        <input type="hidden" name="MAX_FILE_SIZE" value="170000" />
        <input type="file" id="archivos" name="archivos" size="10" multiple="multiple" accept="image/jpg, image/jpeg, image/png, image/gif" /> 
        <input type="submit" id="i_submit" value="Subir" />
    </form>

    <ul id="tmp_imgs"></ul>

</body>
</html>
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}

Etiquetas: file, input, type
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:01.