Foros del Web » Programando para Internet » Javascript »

añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple file

Estas en el tema de añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple file en el foro de Javascript en Foros del Web. Hola a todos Primero comentaros: No tengo ni idea de JavaScript. Dicho esto mi problema... Buscando y rebuscando he encontrado un script en javascript que ...
  #1 (permalink)  
Antiguo 30/03/2008, 03:46
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple file

Hola a todos
Primero comentaros: No tengo ni idea de JavaScript. Dicho esto mi problema...

Buscando y rebuscando he encontrado un script en javascript que hace exactamente el efecto que busco, (mostrar un solo campo de input file para seleccionar un numero limitado de archivos, muy al estilo de GMAIL) con un codigo muy ligero.

Mi problema surge en que necesito modificarlo para que cada campo de input file oculto que genere añada name="userfile[]".

Os paso el codigo del script que se encuentra en:
http://the-stickman.com/web-developm...-file-element/

Código PHP:
/**
 * Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *
 *   2. Create a DIV for the output to be written to
 *      eg. <div id="files_list"></div>
 *
 *   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
 *
 *   4. Add the first element
 *      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
 *
 *   5. That's it.
 *
 *   You might (will) want to play around with the addListRow() method to make the output prettier.
 *
 *   You might also want to change the line 
 *       element.name = 'file_' + this.count;
 *   ...to a naming convention that makes more sense to you.
 * 
 * Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *
 * Credit:
 *   If you're nice, you'll leave this bit:
 *  
 *   Class by Stickman -- http://www.the-stickman.com
 *      with thanks to:
 *      [for Safari fixes]
 *         Luis Torrefranca -- http://www.law.pitt.edu
 *         and
 *         Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
 *      [for duplicate name bug]
 *         'neal'
 */
function MultiSelectorlist_targetmax ){

    
// Where to write the list
    
this.list_target list_target;
    
// How many elements?
    
this.count 0;
    
// How many elements?
    
this.id 0;
    
// Is there a maximum?
    
if( max ){
        
this.max max;
    } else {
        
this.max = -1;
    };
    
    
/**
     * Add a new file input element
     */
    
this.addElement = function( element ){

        
// Make sure it's a file input element
        
if( element.tagName == 'INPUT' && element.type == 'file' ){

            
// Element name -- what number am I?
            
element.name 'file_' this.id++;

            
// Add reference to this object
            
element.multi_selector this;

            
// What to do when a file is selected
            
element.onchange = function(){

                
// New file input
                
var new_element document.createElement'input' );
                
new_element.type 'file';

                
// Add new element
                
this.parentNode.insertBeforenew_elementthis );

                
// Apply 'update' to element
                
this.multi_selector.addElementnew_element );

                
// Update list
                
this.multi_selector.addListRowthis );

                
// Hide this: we can't use display:none because Safari doesn't like it
                
this.style.position 'absolute';
                
this.style.left '-1000px';

            };
            
// If we've reached maximum number, disable input element
            
if( this.max != -&& this.count >= this.max ){
                
element.disabled true;
            };

            
// File element counter
            
this.count++;
            
// Most recent element
            
this.current_element element;
            
        } else {
            
// This can only be applied to file input elements!
            
alert'Error: not a file input element' );
        };

    };

    
/**
     * Add a new row to the list of files
     */
    
this.addListRow = function( element ){

        
// Row div
        
var new_row document.createElement'div' );

        
// Delete button
        
var new_row_button document.createElement'input' );
        
new_row_button.type 'button';
        
new_row_button.value 'Delete';

        
// References
        
new_row.element element;

        
// Delete function
        
new_row_button.onclick= function(){

            
// Remove element from form
            
this.parentNode.element.parentNode.removeChildthis.parentNode.element );

            
// Remove this row from the list
            
this.parentNode.parentNode.removeChildthis.parentNode );

            
// Decrement counter
            
this.parentNode.element.multi_selector.count--;

            
// Re-enable input element (if it's disabled)
            
this.parentNode.element.multi_selector.current_element.disabled false;

            
// Appease Safari
            //    without it Safari wants to reload the browser window
            //    which nixes your already queued uploads
            
return false;
        };

        
// Set row value
        
new_row.innerHTML element.value;

        
// Add button
        
new_row.appendChildnew_row_button );

        
// Add it to the list
        
this.list_target.appendChildnew_row );
        
    };

}; 
Gracias de antemano

Última edición por brainstorm; 30/03/2008 a las 03:56
  #2 (permalink)  
Antiguo 30/03/2008, 04:51
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

El problema de crear controles dinámicamente no es ponerle un nombre, sino poderlo usar por el nombre con explorer, ya que estos controles no suele reconocerlos, pero si no piensas usar un script luego puedes hacer así:

element.name = 'userfile[]';
ó
element.setAttribute("name", "userfile[]");

Ya lo tenías en el script que nos has mostrado, pero si piensas usar ese control mediante un script, y quieres que funcione en explorer deberías tener un control ya definido y clonarlo...

<input type="file" onchange="x=this.cloneNode(true); x['value'] = ''; this.parentNode.appendChild(x); this.disabled = true;" name="userfile[];" />

Puedes ver un artículo aquí: Controles creados dinámicamente

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #3 (permalink)  
Antiguo 30/03/2008, 05:33
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Faltaba comentar que los controles deshabilitados no se enviarían, así que faltaría algo así:

<form onsubmit="for (i = 0; i < this['userfile[]'].length; i++) this['userfile[]'][i].disabled = false" ...

Cuando se añaden también puede hacerse con insertBefor, por si hay más controles...
Código:
this.parentNode.insertBefore(x, this.nextSibling);
También podríamos ocultar los ficheros asignados con estilos, o a la vez que se generan nuevos campos files generar saltos de línea... pero eso ya queda de tu parte...

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #4 (permalink)  
Antiguo 30/03/2008, 07:16
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

En primer lugar gracias por contestar caricatos.

He probado sustituyendo

Código PHP:
<input id="my_file_element" type="file" name="userfile[]" 
por...

Código PHP:
<input id="my_file_element" type="file" onchange="x=this.cloneNode(true); x['value'] = ''; this.parentNode.appendChild(x); this.disabled = true;" name="userfile[];" /> 
Pero no he conseguido nada.
He probado de diversos modos pero cuando he conseguido que efectivamente se añadieran la etiqueta name="userfile[]" entonces se me liaba todo y aparecian los input desperdigados.

Tambien he visitado la pagina que me has indicado pero como que me pierdo.
Como he indicando, ni idea de JavaScript.


Intento hacerlo funcionar es en la seccion Anadir fotografias de la pagina...
http://www.anthelio.com/clasificados...luntariado-ong pero no quiero usar JQuery ni nada porque lo quiero ligero ligero.

Ayuda para quien no tiene ni idea de Javascript ???? se que suena mal... pero un plan tipo sustituye esto por esto otro.



Debo comentar que el script original http://the-stickman.com/web-developm...-file-element/ indica que el formulario donde debe funcionar debe contener:
Código PHP:
<body>
<
form enctype="multipart/form-data" action="your_script_here.script" method "post">
    <!-- 
The file element -- NOTEit has an ID -->
    <
input id="my_file_element" type="file" name="file_1" >
    <
input type="submit">
</
form>
Files:
<!-- 
This is where the output will appear -->
<
div id="files_list"></div>
<
script>
    <!-- 
Create an instance of the multiSelector class, pass it the output target and the max number of files -->
    var 
multi_selector = new MultiSelectordocument.getElementById'files_list' ), );
    <!-- 
Pass in the file element -->
    
multi_selector.addElementdocument.getElementById'my_file_element' ) );
</script>
</body> 
  #5 (permalink)  
Antiguo 30/03/2008, 10:42
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Has tenido el eterno problema del "copy & paste" sin revisar el código... es que dentro del atributo name has puesto un carácter de más (un ";")... ya que copias y pegas, voy a ponerte el código bueno:

Código:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
	http://www.caricatos.net/probador
</title>

</head>
<body>

<form onsubmit="for (i = 0; i < this['userfile[]'].length; i++) this['userfile[]'][i].disabled = false" action="javascript: alert('Ok')" >


<input type="file" onchange="x=this.cloneNode(true); x['value'] = ''; this.parentNode.insertBefore(x, this.nextSibling); this.disabled = true;" name="userfile[]" />

<button type="submit"> enviar </button>

</form>

</body>
</html>
He cambiado el appendChild por un insertBefore como comenté anteriormente.

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #6 (permalink)  
Antiguo 30/03/2008, 11:34
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola caricatos ehh... te estoy agradecido pero va a ser que no va.

Te cuento...
Dejando el archivo JavaScript externo tal cual sin tocar.

El Html dejandolo asi no añade las famosas etiquetas name="userfile[]" a los campos que genera pero los ocualta los nuevos campos y da la sensacion de estar usando todo el rato el mismo input
Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<
html>
<
head>
<
title>
    
http://www.caricatos.net/probador
</title>
<
script language="javascript" src="multifile.js"></script>
</head>
<body>

<form onsubmit="for (i = 0; i < this['userfile[]'].length; i++) this['userfile[]'][i].disabled = false" action="javascript: alert('Ok')" >

<input id="my_file_element" type="file" onchange="x=this.cloneNode(true); x['value'] = ''; this.parentNode.insertBefore(x, this.nextSibling); this.disabled = true;" name="userfile[]" />
<div id="files_list"></div>
<button type="submit"> enviar </button>

</form>

<script> 
    <!-- Create an instance of the multiSelector class, pass it the output target and the max number of files --> 
    var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 ); 
    <!-- Pass in the file element --> 
    multi_selector.addElement( document.getElementById( 'my_file_element' ) ); 
</script>

</body>
</html> 
En cambio si lo dejo asi funciona a medias pues se añaden los name="userfile[]" a cada input pero no se ocultan en pantalla cada uno que se agrega y no se produce el efecto de estar usando el mismo input todo el rato (tipo GMAIL).

Código PHP:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<
html>
<
head>
<
title>
    
http://www.caricatos.net/probador
</title>
<
script language="javascript" src="multifile.js"></script>
</head>
<body>

<form onsubmit="for (i = 0; i < this['userfile[]'].length; i++) this['userfile[]'][i].disabled = false" action="javascript: alert('Ok')" >

<input id="my_file_element" type="file" onchange="x=this.cloneNode(true); x['value'] = ''; this.parentNode.insertBefore(x, this.nextSibling); this.disabled = true;" name="userfile[]" />
<div id="files_list"></div>
<button type="submit"> enviar </button>

</form>
</body>
</html> 
  #7 (permalink)  
Antiguo 30/03/2008, 14:49
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Desde luego que siempre hay que hacer algunos retoques... por ejemplo, si quieres que parezca que siempre usas el mismo input, debes cambiar lo de this.disabled = true por this.style.display = 'none'... además parece que hay una zona para listar esos archivos... será cuestión de trabajar un poco.

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #8 (permalink)  
Antiguo 31/03/2008, 04:19
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Este mensaje es tan solo para darte las gracias por todo caricatos.

Jugare un poco con el codigo pero creo que no voy a implementar al final el script al buscar informacion he visto que el principal problema viene mas bien por el envio y no por la propia seleccion de archivos, es decir no es tan conveniente permitir al usuario subir de golpe 9 archivos que era lo que tenia que pensado permitir elegir.

Por cierto caricatos lo ultimo que me has dicho funcionaba perfectamente pero como has dicho habria que modificarlo bastante para que se mostraran los archivos seleccionados listados, y le faltaria la funcion para "quitar" los archivos seleccionados, y no tengo ni idea como hacerlo.

Lo dicho gracias caricatos
  #9 (permalink)  
Antiguo 31/03/2008, 04:31
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Entonces queda pendiente por si en el futuro te interesa implementarlo (de todos modos, de quererlo es mejor abrir un tema nuevo antes de revivir temas viejos... ayuda a la participación de otros usuarios... me parece más "enriquecedor")

Y para el tema del listado no pienses que sería tan difícil, tan solo crear una función bastante sencilla, pero como tu dices, muchos ficheros adjuntos no es buena idea (comparto la opinión), y otra cosa importante es que también es preferible no depender mucho de javascript, aunque hoy día todos suelen tenerlo habilitado.

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #10 (permalink)  
Antiguo 31/03/2008, 11:49
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Me piqué con este tema e hice esto:

Código:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>
	http://www.caricatos.net/probador
</title>
<script>
function tag(id) {return document.getElementById(id)};
var actual = total = 0;
var maximo = 5;
function listar(f) {
if (actual == total) {
 
 actual = ++total;
 nuevo = document.createElement("div");
 nuevo.onclick = function() {
  tag("file_" + actual).style.display = "none";
  actual = this.id.substr(9);
  tag("file_" + actual).style.display = "inline";
 }
 nuevo.id = "elemento_" + (actual - 1);
 tag("listado").appendChild(nuevo);
 nuevo.appendChild(document.createTextNode(f.value));
 
 if (total < maximo) {
  nuevof = f.cloneNode(true);
  f.style.display = "none";
  nuevof['value'] = "";
  nuevof.id = "file_" + actual;
  f.parentNode.insertBefore(nuevof, f.nextSibling);
 }
 else {
   tag("oculto").style.display = "none";
   actual = 4;
 }
}
else {
// tag("listado").replaceNode(tag("elemento_" + actual).firstChild, document.createTextNode(f.value));
 tag("elemento_" + actual).innerHTML = f.value;
}
}
</script>
</head>
<body>

<form action="javascript: alert('Ok')" >
<input type="file" onchange="listar(this)" name="userfile[]" id="file_0" size="50" />
<button type="submit"> enviar </button>
</form>
<div id="listado" style="position: relative">
<div id="oculto" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: transparent"></div>
</div>
</body>
</html>
Hay cosas para mejorar, pero en FF funciona.

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #11 (permalink)  
Antiguo 31/03/2008, 16:24
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Muy buenooo.
Ligero y eficaz.

No se si seras administrador, pero yo lo pondria en el indice de FAQ abriendo un nuevo POST porque he estado buscando una solucion a esto, en los primeros 50 + o - resultados de google y si bien las hay muy elegantes implicaban mucho codigo KB o necesitaban JQuery, prototype... o no se podia añadir la etiqueta name como el que ha originado el post.

En IE 7 funciona perfecto. Solo una cosa si le añades un enlace con "eliminar" o "borrar" para cada archivo enumerado y que al pulsarlo lo borrara tanto el <div id="elemento_0">, <div id="elemento_1"> como el input seria perfecto una copia del de gmail pero perfecto.

Se lo pongas o no lo de "elimanar" deberias publicarlo en post del FAQ pues he leido por hay que con el tiempo lo implementaran los navegadores pero ha saber cuando... es decir es una funcion que se necesita y soluciones libianas son de agradecer.

GRACIAS.
  #12 (permalink)  
Antiguo 01/04/2008, 01:51
 
Fecha de Ingreso: septiembre-2005
Ubicación: España
Mensajes: 78
Antigüedad: 18 años, 7 meses
Puntos: 0
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

hola caricatos.
al final lo publicastes en el faq, pero te quiero comentar la version que publicaste en este post funcionaba correctamente en IE6 IE7 y FF mientras que la version que publicaste en el FAQ tiene un problema en IE6...
Si seleccionas uno o varios archivos pero menos de 5, estos se muestran listados, correctamente, pero sin pinchas en alguno de ellos desaparece el input de pantalla, y el script arroja un error.

Por fa... currate el borrar un archivo seleccionado... je je, es broma pero a mi me vendria genial.

Un saludo.
  #13 (permalink)  
Antiguo 01/04/2008, 02:34
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Re: añadir name="userfile[]" a script de http://the-stickman.com/ de upload multiple

Hola:

Aunque me extraña lo que comentas, voy a mirar el problema y estoy pensando en lo que planteas sobre borrar elementos... pero también debo hacer otras cosillas mías, así que no sé cuanto tardaré (si lo consigo, of course)... por lo pronto acabo de proponerlo como desafío para que quede "de lujo".

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
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 04:19.