Cambiar el texto predeterminado en input type = "file"?


Quiero cambiar el texto predeterminado en el botón que es "Choose File" cuando usamos input="file".

introduzca la descripción de la imagen aquí

¿Cómo puedo hacer esto? También como se puede ver en el botón de imagen está en el lado izquierdo del texto. ¿Cómo puedo ponerlo en el lado derecho del texto?

Author: Harry Joy, 2011-02-28

14 answers

Cada navegador tiene su propia representación del control y, como tal, no puede cambiar el texto ni la orientación del control.

Hay algunos "tipo de" hacks que puede querer probar si desea un html/css solución en lugar de un Flash o solución silverlight .

Http://www.quirksmode.org/dom/inputfile.html

Http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom

Personalmente, debido a que la mayoría de los usuarios se adhieren a su navegador de elección, y por lo tanto, probablemente estén acostumbrados a ver el control en la variante de representación predeterminada, probablemente se confundirían si vieran algo diferente (dependiendo del tipo de usuarios con los que esté tratando).

 37
Author: Shiv Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 15:02:31

Utilice el atributo "for" de label para input.

<div>
  <label for="files" class="btn">Select Image</label>
  <input id="files" style="visibility:hidden;" type="file">
</div>
A continuación se muestra el código para obtener el nombre del archivo cargado

$("#files").change(function() {
  filename = this.files[0].name
  console.log(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
      <label for="files" class="btn">Select Image</label>
      <input id="files" style="visibility:hidden;" type="file">
    </div>
 98
Author: algometrix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 18:37:49

Esto podría ayudar a alguien en el futuro, puede estilizar la etiqueta para la entrada como desee y poner todo lo que desee dentro de ella y ocultar la entrada con display none.

Funciona perfectamente en Cordova con iOS

<link href="https://cdnjs.cloudflare.com/ajax/libs/ratchet/2.0.2/css/ratchet.css" rel="stylesheet"/>
<label for="imageUpload" class="btn btn-primary btn-block btn-outlined">Seleccionar imagenes</label>
<input type="file" id="imageUpload" accept="image/*" style="display: none">
 18
Author: Paulo Mogollón,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-05 22:31:45

Creo que esto es lo que quieres:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <button style="display:block;width:120px; height:30px;" onclick="document.getElementById('getFile').click()">Your text here</button>
  <input type='file' id="getFile" style="display:none">
</body>

</html>
 10
Author: 1Cr18Ni9,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 11:10:19

No es posible. De lo contrario, es posible que deba usar Silverlight o Flash upload control.

 7
Author: Anuraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-28 06:01:05

Aquí cómo puedes hacerlo:

jQuery:

$(function() {
  $("#labelfile").click(function() {
    $("#imageupl").trigger('click');
  });
})

Css

.file {
  position: absolute;
  clip: rect(0px, 0px, 0px, 0px);
  display: block;
}
.labelfile {
  color: #333;
  background-color: #fff;
  display: inline-block;
  margin-bottom: 0;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  white-space: nowrap;
  padding: 6px 8px;
  font-size: 14px;
  line-height: 1.42857143;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

Código HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="margin-top:4px;">
  <input name="imageupl" type="file" id="imageupl" class="file" />
  <label class="labelfile" id="labelfile"><i class="icon-download-alt"></i> Browse File</label>
</div>
 3
Author: Tushar Shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 13:33:06

Usando Bootstrap puedes hacer esto como el siguiente código.

<!DOCTYPE html>
<html lang="en">
<head>
<style>

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}
</style>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <span class="btn btn-file">Upload image from here<input type="file">
</body>
</html>
 2
Author: Rana Aalamgeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 12:31:47

Hice un script y lo publiqué en GitHub: get Seleccione archivo.js Fácil de usar, siéntase libre de clonar.


HTML

<input type=file hidden id=choose name=choose>
<input type=button onClick=getFile.simulate() value=getFile>
<label id=selected>Nothing selected</label>


JS

var getFile = new selectFile;
getFile.targets('choose','selected');


DEMO

Jsfiddle.net/Thielicious/4oxmsy49/

 2
Author: Thielicious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 14:06:51

Actualización 2017:

He investigado cómo se podría lograr esto. Y la mejor explicación/tutorial está aquí: https://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way /

Escribiré un resumen aquí en caso de que no esté disponible. Así que deberías tener HTML:

<input type="file" name="file" id="file" class="inputfile" />
<label for="file">Choose a file</label>

Luego oculta la entrada con CSS:

.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;}

Luego dale estilo a la etiqueta:

.inputfile + label {
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: black;
display: inline-block;
}

Luego opcionalmente puede agregar JS para mostrar el nombre de la archivo:

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;
});
});

Pero realmente solo lee el tutorial y descarga la demo, es realmente bueno.

 2
Author: user3784950,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-30 13:31:02

Usaría un button para activar el input:

<button onclick="document.getElementById('fileUpload').click()">Open from File...</button>
<input type="file" id="fileUpload" name="files" style="display:none" />

Rápido y limpio.

 1
Author: Sony Santos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-28 17:45:42

Esto debería funcionar:

Entrada. className ::-webkit-file-upload-button { contenido de estilo.. }

 0
Author: Andrius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-29 10:56:15

Déjame añadir un hack que usé. Quería tener una sección que te permitiera arrastrar y soltar archivos, y quería que la sección de arrastrar y soltar fuera clicable junto con el botón de carga original.

Así es como se veía cuando terminé (menos la capacidad de arrastrar y soltar, hay muchos tutoriales sobre cómo hacerlo).

Y luego creé una serie de entradas de blog que son principalmente sobre botones de carga de archivos.

 0
Author: Mr. Me,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-08 01:52:08

Ok muy simple manera pura css de crear su archivo de entrada personalizado.

Use etiquetas, pero como sabe de respuestas anteriores, label no invoca onclick función en Firefox, puede ser un error, pero no importa con lo siguiente.

<label for="file"  class="custom-file-input"><input type="file"  name="file" class="custom-file-input"></input></label>

Lo que haces es darle estilo a la etiqueta para que se vea como quieres

    .custom-file-input {
        color: transparent;/* This is to take away the browser text for file uploading*/
        /* Carry on with the style you want */
        background: url(../img/doc-o.png);
        background-size: 100%;
        position: absolute;
        width: 200px;
        height: 200px;
        cursor: pointer;
        top: 10%;
        right: 15%;
    }

Ahora simplemente oculte el botón de entrada real, pero no puede configurarlo en visability: hidden

Así que haga invisible configurando opacity: 0;

input.custom-file-input {
    opacity: 0;
    position: absolute;/*set position to be exactly over your input*/
    left: 0;
    top: 0;
}

Ahora como usted puede ser que tenga noté que tengo la misma clase en mi etiqueta que en mi campo de entrada, es decir, porque quiero que ambos tengan el mismo estilo, por lo que donde quiera que haga clic en la etiqueta, en realidad está haciendo clic en el campo de entrada invisible.

 0
Author: Jadin Hornsby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-29 08:43:43

Puede utilizar este enfoque, funciona incluso si una gran cantidad de entradas de archivos.

const fileBlocks = document.querySelectorAll('.file-block')
const buttons = document.querySelectorAll('.btn-select-file')

;[...buttons].forEach(function (btn) {
  btn.onclick = function () {
    btn.parentElement.querySelector('input[type="file"]').click()
  }
})

;[...fileBlocks].forEach(function (block) {
  block.querySelector('input[type="file"]').onchange = function () {
    const filename = this.files[0].name

    block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename
  }
})
.btn-select-file {
  border-radius: 20px;
}

input[type="file"] {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="file-block">
  <button class="btn-select-file">Select Image 1</button>
  <input type="file">
</div>
<br>
<div class="file-block">
  <button class="btn-select-file">Select Image 2</button>
  <input type="file">
</div>
 0
Author: Илья Зеленько,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 09:59:02