Foros del Web » Programando para Internet » Javascript »

Se puede simular un <input type="file>??

Estas en el tema de Se puede simular un <input type="file>?? en el foro de Javascript en Foros del Web. Buenas! Necesito que al hacer click sobre un link, se abra el file browser... He mirado y mirado cómo se puede hacer, pero en general ...
  #1 (permalink)  
Antiguo 18/11/2010, 02:38
Avatar de Devil Akuma  
Fecha de Ingreso: mayo-2004
Mensajes: 104
Antigüedad: 19 años, 11 meses
Puntos: 0
Se puede simular un <input type="file>??

Buenas!

Necesito que al hacer click sobre un link, se abra el file browser... He mirado y mirado cómo se puede hacer, pero en general me parece bastante complicado. A través de capas sobre puestas y plugins de jquery...
¿Alguien me puyede echar una mano?
Sencillamente necesito hacer algo como el "Attach file" de gmail. Simplemente abrir un navegador de ficheros y que recoja su path asociado...

Un saludo
__________________
CINeol has you...
  #2 (permalink)  
Antiguo 18/11/2010, 08:23
Avatar de BloodShadow  
Fecha de Ingreso: marzo-2010
Ubicación: El Salvador
Mensajes: 393
Antigüedad: 14 años, 1 mes
Puntos: 52
Respuesta: Se puede simular un <input type="file>??

Hola Devil Akuma te dejo este codigo, solo copia y pega y has los respectivos cambios de estilos y la imagen :D

En el HTML

Código HTML:
Ver original
  1. <form id="frmPicture" name="frmChangePicture" action="" method="post" enctype="multipart/form-data">
  2.   <input type="hidden" name="Change" value="1">
  3.   <label class="cabinet" style="background: url(img/site_new/btn-change-photo.png) 0 0 no-repeat;">
  4.   <input type="file" id="filein" class="file" style="width:115px; cursor: pointer;" name="per-image" onchange="document.getElementById('frmPicture').submit();" />
  5.   </label>
  6. </form>

y en el head agrega este javascript

Código Javascript:
Ver original
  1. // STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
  2. if (!window.SI) { var SI = {}; };
  3. SI.Files =
  4. {
  5.     htmlClass : 'SI-FILES-STYLIZED',
  6.     fileClass : 'file',
  7.     wrapClass : 'cabinet',
  8.     wrapClass2 : 'cabinet2',
  9.    
  10.     fini : false,
  11.     able : false,
  12.     init : function()
  13.     {
  14.         this.fini = true;
  15.        
  16.         var ie = 0 //@cc_on + @_jscript_version
  17.         if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
  18.         this.able = true;
  19.        
  20.         var html = document.getElementsByTagName('html')[0];
  21.         html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
  22.     },
  23.    
  24.     stylize : function(elem)
  25.     {
  26.         if (!this.fini) { this.init(); };
  27.         if (!this.able) { return; };
  28.        
  29.         elem.parentNode.file = elem;
  30.         elem.parentNode.onmousemove = function(e)
  31.         {
  32.             if (typeof e == 'undefined') e = window.event;
  33.             if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
  34.             {
  35.                 e.pageX = e.clientX + document.documentElement.scrollLeft;
  36.                 e.pageY = e.clientY + document.documentElement.scrollTop;
  37.             };
  38.  
  39.             var ox = oy = 0;
  40.             var elem = this;
  41.             if (elem.offsetParent)
  42.             {
  43.                 ox = elem.offsetLeft;
  44.                 oy = elem.offsetTop;
  45.                 while (elem = elem.offsetParent)
  46.                 {
  47.                     ox += elem.offsetLeft;
  48.                     oy += elem.offsetTop;
  49.                 };
  50.             };
  51.  
  52.             var x = e.pageX - ox;
  53.             var y = e.pageY - oy;
  54.             var w = this.file.offsetWidth;
  55.             var h = this.file.offsetHeight;
  56.  
  57.             this.file.style.top     = y - (h / 2)  + 'px';
  58.             this.file.style.left    = x - (w - 30) + 'px';
  59.         };
  60.     },
  61.    
  62.     stylizeById : function(id)
  63.     {
  64.         this.stylize(document.getElementById(id));
  65.     },
  66.    
  67.     stylizeAll : function()
  68.     {
  69.         if (!this.fini) { this.init(); };
  70.         if (!this.able) { return; };
  71.        
  72.         var inputs = document.getElementsByTagName('input');
  73.         for (var i = 0; i < inputs.length; i++)
  74.         {
  75.             var input = inputs[i];
  76.             if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
  77.             {
  78.                 this.stylize(input);
  79.                                
  80.             };
  81.             if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass2) != -1)
  82.             {
  83.                 this.stylize(input);
  84.             };
  85.             };
  86.     }
  87. };
  #3 (permalink)  
Antiguo 18/11/2010, 08:34
Avatar de Devil Akuma  
Fecha de Ingreso: mayo-2004
Mensajes: 104
Antigüedad: 19 años, 11 meses
Puntos: 0
Respuesta: Se puede simular un <input type="file>??

Buenas!

He puesto el código tal y como me has comentado... y no me ha cambiado nada. En IE se veía el input más pequeño, pero en Firefox exactamente igual. ¿Puede ser que lo haya puesto mal?

Código HTML:
Ver original
  1. <script type="text/javascript">
  2. if (!window.SI) { var SI = {}; };
  3. SI.Files =
  4. {
  5.     htmlClass : 'SI-FILES-STYLIZED',
  6.     fileClass : 'file',
  7.     wrapClass : 'cabinet',
  8.     wrapClass2 : 'cabinet2',
  9.    
  10.     fini : false,
  11.     able : false,
  12.     init : function()
  13.     {
  14.         this.fini = true;
  15.        
  16.         var ie = 0 //@cc_on + @_jscript_version
  17.         if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
  18.         this.able = true;
  19.        
  20.         var html = document.getElementsByTagName('html')[0];
  21.         html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
  22.     },
  23.    
  24.     stylize : function(elem)
  25.     {
  26.         if (!this.fini) { this.init(); };
  27.         if (!this.able) { return; };
  28.        
  29.         elem.parentNode.file = elem;
  30.         elem.parentNode.onmousemove = function(e)
  31.         {
  32.             if (typeof e == 'undefined') e = window.event;
  33.             if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
  34.            {
  35.                e.pageX = e.clientX + document.documentElement.scrollLeft;
  36.                 e.pageY = e.clientY + document.documentElement.scrollTop;
  37.             };
  38.  
  39.             var ox = oy = 0;
  40.             var elem = this;
  41.             if (elem.offsetParent)
  42.             {
  43.                 ox = elem.offsetLeft;
  44.                 oy = elem.offsetTop;
  45.                 while (elem = elem.offsetParent)
  46.                 {
  47.                     ox += elem.offsetLeft;
  48.                     oy += elem.offsetTop;
  49.                 };
  50.             };
  51.  
  52.             var x = e.pageX - ox;
  53.             var y = e.pageY - oy;
  54.             var w = this.file.offsetWidth;
  55.             var h = this.file.offsetHeight;
  56.  
  57.             this.file.style.top     = y - (h / 2)  + 'px';
  58.             this.file.style.left    = x - (w - 30) + 'px';
  59.         };
  60.     },
  61.    
  62.     stylizeById : function(id)
  63.     {
  64.         this.stylize(document.getElementById(id));
  65.     },
  66.    
  67.     stylizeAll : function()
  68.     {
  69.         if (!this.fini) { this.init(); };
  70.         if (!this.able) { return; };
  71.        
  72.         var inputs = document.getElementsByTagName('input');
  73.         for (var i = 0; i < inputs.length; i++)
  74.        {
  75.            var input = inputs[i];
  76.            if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
  77.            {
  78.                this.stylize(input);
  79.                                
  80.            };
  81.            if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass2) != -1)
  82.            {
  83.                this.stylize(input);
  84.            };
  85.            };
  86.    }
  87. };
  88. </head>
  89.  
  90. <form id="frmPicture" name="frmChangePicture" action="" method="post" enctype="multipart/form-data">
  91.   <input type="hidden" name="Change" value="1">
  92.   <label class="cabinet" style="background: url(img/site_new/btn-change-photo.png) 0 0 no-repeat;">
  93.   <input type="file" id="filein" class="file" style="width:115px; cursor: pointer;" name="per-image" onchange="document.getElementById('frmPicture').submit();" />
  94.   </label>
  95. </form>
  96. </html>
__________________
CINeol has you...
  #4 (permalink)  
Antiguo 18/11/2010, 08:47
Avatar de BloodShadow  
Fecha de Ingreso: marzo-2010
Ubicación: El Salvador
Mensajes: 393
Antigüedad: 14 años, 1 mes
Puntos: 52
Respuesta: Se puede simular un <input type="file>??

Si perdón, me hizo falta un par de cosas... Ya lo arregle, ahora te dejo completo el html y su respectivos script y css, solo agrega una imagen buscar.png para q veas resultados, luego tu la cambias a tu antojo... Guarda todo en la misma carpeta y me cuentas si te sirve... yo lo acabo de hacer y si me funciona, estare al tanto de tu respuesta...

index.html
Código HTML:
Ver original
  1.     <head>     
  2.         <title>TVOffer</title>
  3.         <link rel="stylesheet" type="text/css" href="styles.css" />
  4.         <script language="javascript" type="text/javascript" src="si.files.js"></script>
  5.         <script type="text/javascript">
  6.             SI.Files.stylizeAll();
  7.         </script>
  8.     </head>
  9.     <body>
  10.         <form id="frmPicture" name="frmChangePicture" style="padding: 0px; margin: 0px;" action="" method="post" enctype="multipart/form-data">
  11.             <input type="hidden" name="Change" value="1">
  12.             <label class="cabinet" style="background: url(btn-find-photo-es.png) 0 0 no-repeat;">
  13.                 <input type="file" id="filein" class="file" style="width:115px; cursor: pointer;" name="per-image" onchange="document.getElementById('frmPicture').submit();" />
  14.             </label>
  15.         </form>
  16.     </body>
  17. </html>


styles.css
Código CSS:
Ver original
  1. .SI-FILES-STYLIZED label.cabinet            { width:115px; height:26px; _height:26px; background: url(../img/btn-operation.png) 0 0 no-repeat; display: block; overflow: hidden; cursor: pointer; }
  2.     .SI-FILES-STYLIZED label.cabinet input.file { position:relative; height:100%; width:auto; cursor: pointer; opacity: 0; -moz-opacity: 0; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); }
  3.  
  4.     .SI-FILES-STYLIZED label.cabinet2            { width:108px; height:28px; _height:28px; background: url(../img/btn-find-photo.png) 0 0 no-repeat; display: block; overflow: hidden; cursor: pointer; }
  5.     .SI-FILES-STYLIZED label.cabinet2 input.file { position:relative; height:100%; width:auto; cursor: pointer; opacity: 0; -moz-opacity: 0; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0); }
  6.  
  7.      /**
  8.      * ACTUALIZACION SQUEEZEBOX
  9.      */  PARA MOSTRAR VIDEOS SWF
  10.     #sbox-window .sbox-content-swf              { overflow:hidden; }

si.files.js

Código Javascript:
Ver original
  1. // STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
  2. if (!window.SI) { var SI = {}; };
  3. SI.Files =
  4. {
  5.     htmlClass : 'SI-FILES-STYLIZED',
  6.     fileClass : 'file',
  7.     wrapClass : 'cabinet',
  8.     wrapClass2 : 'cabinet2',
  9.    
  10.     fini : false,
  11.     able : false,
  12.     init : function()
  13.     {
  14.         this.fini = true;
  15.        
  16.         var ie = 0 //@cc_on + @_jscript_version
  17.         if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
  18.         this.able = true;
  19.        
  20.         var html = document.getElementsByTagName('html')[0];
  21.         html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
  22.     },
  23.    
  24.     stylize : function(elem)
  25.     {
  26.         if (!this.fini) { this.init(); };
  27.         if (!this.able) { return; };
  28.        
  29.         elem.parentNode.file = elem;
  30.         elem.parentNode.onmousemove = function(e)
  31.         {
  32.             if (typeof e == 'undefined') e = window.event;
  33.             if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
  34.             {
  35.                 e.pageX = e.clientX + document.documentElement.scrollLeft;
  36.                 e.pageY = e.clientY + document.documentElement.scrollTop;
  37.             };
  38.  
  39.             var ox = oy = 0;
  40.             var elem = this;
  41.             if (elem.offsetParent)
  42.             {
  43.                 ox = elem.offsetLeft;
  44.                 oy = elem.offsetTop;
  45.                 while (elem = elem.offsetParent)
  46.                 {
  47.                     ox += elem.offsetLeft;
  48.                     oy += elem.offsetTop;
  49.                 };
  50.             };
  51.  
  52.             var x = e.pageX - ox;
  53.             var y = e.pageY - oy;
  54.             var w = this.file.offsetWidth;
  55.             var h = this.file.offsetHeight;
  56.  
  57.             this.file.style.top     = y - (h / 2)  + 'px';
  58.             this.file.style.left    = x - (w - 30) + 'px';
  59.         };
  60.     },
  61.    
  62.     stylizeById : function(id)
  63.     {
  64.         this.stylize(document.getElementById(id));
  65.     },
  66.    
  67.     stylizeAll : function()
  68.     {
  69.         if (!this.fini) { this.init(); };
  70.         if (!this.able) { return; };
  71.        
  72.         var inputs = document.getElementsByTagName('input');
  73.         for (var i = 0; i < inputs.length; i++)
  74.         {
  75.             var input = inputs[i];
  76.             if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
  77.             {
  78.                 this.stylize(input);
  79.                                
  80.             };
  81.             if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass2) != -1)
  82.             {
  83.                 this.stylize(input);
  84.             };
  85.             };
  86.     }
  87. };
  #5 (permalink)  
Antiguo 18/11/2010, 17:46
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Se puede simular un <input type="file>??

Devil Akuma:

Más que complicado, complicadísimo. Yo consegui algo que funciona perfecto.... pero sólo en IE8 y Chrome, lo que equivale a decir que no consegui nada.

El peor con el que tratar, es el firefox, hay que recurrir a mil artimañas.
Por tra parte, si consigues ese efecto, estás privando al usuario de ver que archivo seleccionó (siempre está la posibilidad de que se halla equivocado), he visto varias scripts, incluso la que menciona BloodShadow, no me funcionó en varios aspectos, pero si la quieres probar te sugiero que descargues el código original desde
http://shauninman.com/archive/2007/0...ss_and_the_dom
Si bien no es lo que buscas, para presonalizar el aspecto de un input file, lo que si funciona es
http://www.php-help.ro/wp-content/up...le_styling.zip

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #6 (permalink)  
Antiguo 19/11/2010, 02:35
Avatar de Devil Akuma  
Fecha de Ingreso: mayo-2004
Mensajes: 104
Antigüedad: 19 años, 11 meses
Puntos: 0
Respuesta: Se puede simular un <input type="file>??

Va perfecto, el único problema (cuestión) que tengo ahora es cómo saber si el usuario ha seleccionado algún fichero para lanzar el submit posteriormente. ¿Puedo coger de alguna manera el nombre del fichero del usuario? Y así (además de poder mostrarlo en la página, sabría si ya lo ha seleccionado...)

Estamos cerquita del éxito!
__________________
CINeol has you...
  #7 (permalink)  
Antiguo 19/11/2010, 07:32
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 9 meses
Puntos: 1567
Respuesta: Se puede simular un <input type="file>??

Devil Akuma:

cual de los ejemplos "va perfecto", para ver si se puede hallar una solucion...

saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #8 (permalink)  
Antiguo 19/11/2010, 08:24
Avatar de BloodShadow  
Fecha de Ingreso: marzo-2010
Ubicación: El Salvador
Mensajes: 393
Antigüedad: 14 años, 1 mes
Puntos: 52
Respuesta: Se puede simular un <input type="file>??

Si es que el código que te deje es el que te funciono te digo lo siguiente: Detrás del engaño visual que se hace con este truco... siempre existe un input, asi que puede validar con javascript si el input name="per-image" tiene un string...
Con javascript lo podes hacer así


Código Javascript:
Ver original
  1. <script>
  2.  if(document.getElementById('filein').value == ''){
  3.   alert('Por favor seleccione un archivo para subir') ;
  4.   return false ;
  5.  }
  6. </script>

Solo es un ejemplo... Intenta lo demás por tu mismo, hasta aquí llega mi aporte, es mas que suficiente, si tienes dudas con otra cosa haslo saber... Nos vemos cuidate
  #9 (permalink)  
Antiguo 22/11/2010, 02:41
Avatar de Devil Akuma  
Fecha de Ingreso: mayo-2004
Mensajes: 104
Antigüedad: 19 años, 11 meses
Puntos: 0
Respuesta: Se puede simular un <input type="file>??

Gracias a todos, he conseguido hacerlo funcionar...

Soy capaz de detectar si me han seleccionado algún fichero poniendo en el onready de mi página lo siguiente...

Código Javascript:
Ver original
  1. $('#filein').change(function() {
  2.         //Ha habido un cambio en el input:file, lo mostramos en pantalla
  3.         if($('#filein').val()!=""){
  4.         $("#nombre_fichero").html($('#filein').val());                     
  5.         }                
  6.     });

En Firefox me pone el nombre del fichero y en IE el path entero.

Gracias a todos!
__________________
CINeol has you...

Etiquetas: simular
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:05.