2009-08-19 71 views
77

Este código debería funcionar en IE (ni siquiera lo pruebe en Firefox), pero no es así. Lo que quiero es mostrar el nombre del archivo adjunto. ¿Alguna ayuda?jQuery: obtenga el nombre de archivo seleccionado de <input type = "file" />

<html> 
<head> 
    <title>example</title>  
    <script type="text/javascript" src="../js/jquery.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function(){    
     $("#attach").after("<input id='fakeAttach' type='button' value='attach a file' />");  
     $("#fakeAttach").click(function() {    
     $("#attach").click();   
     $("#maxSize").after("<div id='temporary'><span id='attachedFile'></span><input id='remove' type='button' value='remove' /></div>");   
     $('#attach').change(function(){ 
      $("#fakeAttach").attr("disabled","disabled");   
      $("#attachedFile").html($(this).val()); 
     });   
     $("#remove").click(function(e){ 
      e.preventDefault(); 
      $("#attach").replaceWith($("#attach").clone()); 
      $("#fakeAttach").attr("disabled",""); 
      $("#temporary").remove(); 
     }); 
     }) 
    }); 
    </script> 
</head> 
<body> 
    <input id="attach" type="file" /><span id="maxSize">(less than 1MB)</span>  
</body> 
</html> 
+0

Compruebe mi respuesta, creo que es la mejor y más comprensible forma de lograr esto. – James111

Respuesta

141

Es simplemente tan simple como escribir:

$('input[type=file]').val() 

De todos modos, se sugiere emplear el nombre o atributo ID para seleccionar la entrada. Y con caso, debe tener este aspecto: siguiente

$('input[type=file]').change(function(e){ 
    $in=$(this); 
    $in.next().html($in.val()); 
}); 
+0

¡Gracias! Eso funcionó en el problema anterior (y simplificado) que planteé, pero no funciona en la versión extendida. –

+0

cómo obtener la ruta completa del archivo, el código anterior solo da el nombre del archivo. –

+3

@PHP Sacerdote, no puedes. Los navegadores no exponen ese tipo de información. – zneak

2
//get file input 
var $el = $('input[type=file]'); 
//set the next siblings (the span) text to the input value 
$el.next().text($el.val()); 
3

que había usado el que funcionaba correctamente.

$('#fileAttached').attr('value', $('#attachment').val()) 
1

Agregar un botón de reinicio oculto:

<input id="Reset1" type="reset" value="reset" class="hidden" /> 

Haga clic en el botón de reinicio para borrar la entrada.

$("#Reset1").click(); 
+1

¿Puedes hacer clic en un botón oculto? – DaveWalley

19
$('input[type=file]').change(function(e){ 
    $(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name); 
}); 

Este código no se mostrará C:\fakepath\ antes del nombre de archivo en Google Chrome en caso de utilizar .val().

3
<input onchange="readURL(this);" type="file" name="userfile" /> 
<img src="" id="blah"/> 
<script> 
function readURL(input) { 
    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
      $('#blah') 
        .attr('src', e.target.result) 
        .width(150).height(200); 
     }; 

     reader.readAsDataURL(input.files[0]); 
     //console.log(reader); 
     //alert(reader.readAsDataURL(input.files[0])); 
    } 
} 
</script> 
+0

Gracias! Esto fue útil para captar el nombre real del archivo cargado y no la ruta completa. –

+0

Más Bienvenido Evan M –

13

La forma más sencilla es simplemente usar la siguiente línea de jquery, utilizando este no obtiene el sentido /fakepath, se obtiene directamente hacia arriba el archivo que se ha subido:

$('input[type=file]')[0].files[0]; // This gets the file 
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id 

algunos otros comandos útiles son:

para obtener el nombre del fichero:

$('input[type=file]')[0].files[0].name; // This gets the file name 

para obtener el tipo del archivo:

Si tuviera que cargar un archivo PNG, devolvería image/png

$("#imgUpload")[0].files[0].type 

Para obtener el tamaño (en bytes) del archivo:

$("#imgUpload")[0].files[0].size 

Además, no tiene que utilizar estos comandos on('change', puede obtener los valores en cualquier momento, por ejemplo, puede tener una carga de archivo y cuando el uso Hace clic en upload, simplemente usa los comandos que enumeré.

+0

¿Por qué recibí el error No puedo leer la propiedad 'nombre' de indefinido? – Gagantous

-2
<input onchange="readURL(this);" type="file" name="userfile" /> 
<img src="" id="viewImage"/> 
<script> 
function readURL(fileName) { 
    if (fileName.files && fileName.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
      $('#viewImage') 
        .attr('src', e.target.result) 
        .width(150).height(200); 
     }; 

     reader.readAsDataURL(fileName.files[0]); 
    } 
} 
</script> 
Cuestiones relacionadas