Foros del Web » Creando para Internet » HTML »

Previsualizar imagen cargado con un type="file"

Estas en el tema de Previsualizar imagen cargado con un type="file" en el foro de HTML en Foros del Web. Buenas tardes a todos, mi dilema es el siguiente, estoy haceindo un cms para mi pagina, y para darle mas estilo a la subida de ...
  #1 (permalink)  
Antiguo 21/01/2013, 15:30
 
Fecha de Ingreso: enero-2013
Mensajes: 5
Antigüedad: 11 años, 3 meses
Puntos: 0
Pregunta Previsualizar imagen cargado con un type="file"

Buenas tardes a todos, mi dilema es el siguiente, estoy haceindo un cms para mi pagina, y para darle mas estilo a la subida de imagenes quiero previsualizarlos, osea lo cargo con un form type="file" y quiero mostrarlo en un div, buscando por ahi encontre un codigo, donde este es el jquery
Código:
window.imagenVacia = 'data:image/gif;base64,R0lGODlhAQABAI' + 
                     'AAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

window.mostrarVistaPrevia = function mostrarVistaPrevia(){
	
	//Para navegadores antiguos
	if(typeof FileReader !== "function" ){
		jQuery('#infoNombre').text('[Vista previa no disponible]');
		jQuery('#infoTamaño').text('(su navegador no soporta vista previa!)');
		return;
	}
	var Archivos,Lector;
	Archivos = jQuery('#archivo')[0].files;
	if(Archivos.length>0){
		
		Lector = new FileReader();
		Lector.onloadend = function(e){
			var origen,tipo;
			//Envía la imagen a la pantalla
			origen = e.target; //objeto FileReader
			jQuery('#vistaPrevia').attr('src', origen.result);
		};
		Lector.onerror = function(e){
			console.log(e)
		}
		Lector.readAsDataURL(Archivos[0]); 
	}else{
		var objeto = jQuery('#archivo');
		objeto.replaceWith(objeto.val('').clone());
		jQuery('#vistaPrevia').attr('src', window.imagenVacia);
	};


};

//Lee el tipo MIME de la cabecera de la imagen
window.obtenerTipoMIME = function obtenerTipoMIME(cabecera){
	return cabecera.replace(/data:([^;]+).*/, '\$1');
}

jQuery(document).ready(function(){
	
	//Cargamos la imagen "vacía" que actuará como Placeholder
	jQuery('#vistaPrevia').attr('src', window.imagenVacia);

	//El input del archivo lo vigilamos con un "delegado"
	jQuery('#botonera').on('change', '#archivo', function(e){
		window.mostrarVistaPrevia();
	});
	//El botón Cancelar lo vigilamos normalmente
	jQuery('#cancelar').on('click', function(e){
		var objeto = jQuery('#archivo');
		objeto.replaceWith(objeto.val('').clone());
		jQuery('#vistaPrevia').attr('src', window.imagenVacia);
		jQuery('#infoNombre').text('[Seleccione una imagen]');
		jQuery('#infoTamaño').text('');
	});

});
y este el codigo de html
Código HTML:
<div class="contenedor">
....ya esta añadido los scripts y todos eso.....
...muestro el body....																		<div id="marcoVistaPrevia" > <img id="vistaPrevia"  src="" alt="" /> </div> </div> <div id="botonera"> <input id="archivo" type="file" accept="image/*"></input> <input type="text" placeholder="Descripcion"></input> <button type="submit" value="" name="boton" class="btn btn-success"/>Guardar</button> </div> 

...Funciona bien en una parte de mi código, pero si por ejemplo quiero también en otra parte de mi código ya no funciona, solo funciona para el código que mas arriba esta.
Ayudenme por favor, porque llevo dias tratando de ver porque funciona en uno y en el otro no.
  #2 (permalink)  
Antiguo 21/01/2013, 18:13
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Previsualizar imagen cargado con un type="file"

Probá de no usar jQuery

Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <html lang="es-ar">
  3. <meta charset="utf-8" />
  4. <title>HTML5 FileReader</title>
  5. </head>
  6. <form action="#" method="post" id="subearchivos">
  7.     <input type="file" id="archivos" name="archivos" />
  8.     <div id="vista_previa"><!-- miniatura -->Vista previa</div>
  9.     <input type="submit" id="enviar" name="enviar" />
  10.         <input type="button" value="cancelar"  style="display: none;" onclick="cancela('subearchivos');" id="resetear" />
  11. </form>
  12.     <script>
  13.     if (window.FileReader) {
  14.       function seleccionArchivo(evt) {
  15.         var files = evt.target.files;
  16.         var f = files[0];
  17.         var leerArchivo = new FileReader();
  18.         document.getElementById('resetear').style.display= 'block';
  19.           leerArchivo.onload = (function(elArchivo) {
  20.             return function(e) {
  21.               document.getElementById('vista_previa').innerHTML = '<img src="'+ e.target.result +'" alt="" width="250" />';
  22.             };
  23.           })(f);
  24.    
  25.           leerArchivo.readAsDataURL(f);
  26.       }
  27.      } else {
  28.       document.getElementById('vista_previa').innerHTML = "El navegador no soporta vista previa";
  29.     }
  30.    
  31.       document.getElementById('archivos').addEventListener('change', seleccionArchivo, false);
  32.      
  33.       function cancela(elForm){
  34. document.getElementById(elForm).reset();
  35. if (window.FileReader) {
  36. document.getElementById('vista_previa').innerHTML = "Vista Previa";
  37. }else{
  38. document.getElementById('vista_previa').innerHTML = "El navegador no soporta vista previa";
  39. }
  40.         document.getElementById('resetear').style.display= 'none';
  41.       }
  42.     </script>
  43.    
  44.  </body>
  45. </html>

El mensaje vista previa bien puede ser una imagen.
El problema con esta api sigue siendo la compatibilidad, IE9 y Safari no la soportan, para algo 100% compatible necesitas subir la imagen al server y mostrarla, por ejemplo en un iframe oculto
SAludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.

Etiquetas: javascript, jquery
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 08:41.