Vista previa de imagen en el navegador
by roimergarcia
HTML
<div id='botonera'>
<input id="archivo" type="file" accept="image/*"></input>
<input id="cancelar" type="button" value="Cancelar"></input>
</div>
<div class="contenedor">
<div class="titulo">
<span>Vista Previa:</span>
<span id="infoNombre">[Seleccione una imagen]</span><br/>
<span id="infoTamaño"></span>
</div>
<div id="marcoVistaPrevia">
<img id="vistaPrevia" src="" alt="" />
</div>
</div>
CSS
.titulo{ font-size: 12pt; font-weight: bold; height: 30pt;}
#marcoVistaPrevia{
border: 1px solid #008000;
width: 400px;
height: 400px;
}
#vistaPrevia{
max-width: 400px;
max-height: 400px;
}
JavaScript
//Este string contiene una imagen de 1px*1px color blanco
window.imagenVacia = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
window.mostrarVistaPrevia = function mostrarVistaPrevia() {
var Archivos, Lector;
//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;
}
Archivos = jQuery('#archivo')[0].files;
if (Archivos.length > 0) {
Lector = new FileReader();
Lector.onloadend = function(e) {
var origen, tipo;
//Envia la imagen a la pantalla
origen = e.target; //objeto FileReader
//Prepara la información sobre la imagen
tipo = window.obtenerTipoMIME(origen.result.substring(0, 30));
jQuery('#infoNombre').text(Archivos[0].name + ' (Tipo: ' + tipo + ')');
jQuery('#infoTamaño').text('Tamaño: ' + e.total + ' bytes');
//Si el tipo de archivo es válido lo muestra,
//sino muestra un mensaje
if (tipo !== 'image/jpeg' && tipo !== 'image/png' && tipo !== 'image/gif') {
jQuery('#vistaPrevia').attr('src', window.imagenVacia);
alert('El formato de imagen no es válido: debe seleccionar una imagen JPG, PNG o GIF.');
} else {
jQuery('#vistaPrevia').attr('src', origen.result);
window.obtenerMedidas();
}
};
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);
jQuery('#infoNombre').text('[Seleccione una imagen]');
jQuery('#infoTamaño').text('');
};
};
//Lee el tipo MIME...