5

Estoy intentando hacer unos inputs tipo file en mi web pero no consigo que cuando se seleccione un archivo se vea cual es, he intentado seguir el ejemplo de aquí: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/

.inputfile {
	width: 0.1px;
	height: 0.1px;
	opacity: 0;
	overflow: hidden;
	position: absolute;
	z-index: -1;
}
.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
<input id="image1" type="file" class="inputfile hidden-xs hidden-md" value="image1" name="image1" required />
<label for="image1" class="my-btn btn-danger"><center>Archivo 1</center></label><br>

Lo que quiero es que cuando yo seleccione un archivo en vez de poner "Archivo 1" ponga el nombre del archivo y no sé como hacerlo, he probado de copiar el código js que hay en esa web pero cuando lo pongo deja de funcionar del todo.

2 respuestas 2

8

Si lo que quieres es simplemente el nombre del fichero entonces lo puedes obtener directamente del input accediendo al atributo name del primer fichero cargado en el input:

document.getElementById('image1').files[0].name;

Sin embargo, si intentas obtener la ruta en la que se encuentra dicho fichero, puedes intentarlo realizando this.value. Sin embargo, como puedes observar, te devuelve una ruta que no es la real del archivo y te lo sustituye por un fakepath. Esto se debe a que por motivos de seguridad no se agrega la ruta en la que el usuario tiene almacenado el fichero.

Tu ejemplo modificado:

document.getElementById('image1').onchange = function () {
  console.log(this.value);
  document.getElementById('fichero').innerHTML = document.getElementById('image1').files[0].name;
}
.inputfile {
	width: 0.1px;
	height: 0.1px;
	opacity: 0;
	overflow: hidden;
	position: absolute;
	z-index: -1;
}
.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
<input id="image1" type="file" class="inputfile hidden-xs hidden-md" value="image1" name="image1" required />
<label id="fichero" for="image1" class="my-btn btn-danger"><center>Archivo 1</center></label><br>

1
  • 1
    Muy útil la forma de acceder al atributo desde el input. Gracias
    – Cesarin
    el 14 oct. 2020 a las 6:56
0

.inputfile {
    width: 0.1px;
    height: 0.1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
}
.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
}
.fileUpload input.upload {
    position: absolute;
    top: 0;
    right: 0;
    margin: 0;
    padding: 0;
    font-size: 20px;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
}
  <input id="image1" type="file" class="inputfile hidden-xs hidden-md" value="image1" name="image1" required />
 <label for="image1" class="my-btn btn-danger"><span>Archivo 1</span></label><br>
    <script>
                   'use strict';

;( function ( document, window, index )
{
    var inputs = document.querySelectorAll( '.inputfile' );
    Array.prototype.forEach.call( inputs, function( input )
    {
        var label    = input.nextElementSibling,
            labelVal = label.innerHTML;

        input.addEventListener( 'change', function( e )
        {
            var fileName = '';
            if( this.files && this.files.length > 1 )
                fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
            else
                fileName = e.target.value.split( '\\' ).pop();

            if( fileName )
                label.querySelector( 'span' ).innerHTML = fileName;
            else
                label.innerHTML = labelVal;
        });

        // Firefox bug fix
        input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
        input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
    });
}( document, window, 0 ));</script>

2
  • Presiona ejecutar y pruebalo. Saludos el 28 dic. 2016 a las 18:18
  • Por sierto pon span en tu html el 28 dic. 2016 a las 18:32

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.