Buen día a todos,
Tengo un formulario con varios campos. Además, el formulario se envía a través del método de datos del formulario usando ajax en un archivo php.
El siguiente es el código javascript que envía los datos del formulario.
$(".update").click(function(){ $.ajax({ url: 'post_reply.php', type: 'POST', contentType:false, processData: false, data: function(){ var data = new FormData(); data.append('image',$('#picture').get(0).files[0]); data.append('body' , $('#body').val()); data.append('uid', $('#uid').val()); return data; }(), success: function(result) { alert(result); }, error: function(xhr, result, errorThrown){ alert('Request failed.'); } }); $('#picture').val(''); $('#body').val(''); });Y, la siguiente es la forma real:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea> <input type=file name=image id=picture > <input name=update value=Send type=submit class=update id=update />Este formulario y javascript funcionan bien como están. Sin embargo, estoy tratando de poder cargar varios archivos en el archivo php usando este único atributo de campo type=file. Tal como está ahora, solo puede tomar un archivo a la vez. ¿Cómo ajusto tanto el formulario como el código javascript para poder manejar cargas de múltiples archivos?
Cualquier ayuda sería muy apreciada.
¡Gracias!
Aquí está ajax, html y php global al que puede acceder. Avísame si te funciona.
// Updated part jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file-'+i, file); }); // Full Ajax request $(".update").click(function(e) { // Stops the form from reloading e.preventDefault(); $.ajax({ url: 'post_reply.php', type: 'POST', contentType:false, processData: false, data: function(){ var data = new FormData(); jQuery.each(jQuery('#file')[0].files, function(i, file) { data.append('file-'+i, file); }); data.append('body' , $('#body').val()); data.append('uid', $('#uid').val()); return data; }(), success: function(result) { alert(result); }, error: function(xhr, result, errorThrown){ alert('Request failed.'); } }); $('#picture').val(''); $('#body').val(''); });HTML actualizado:
<form enctype="multipart/form-data" method="post"> <input id="file" name="file[]" type="file" multiple/> <input class="update" type="submit" /> </form>Ahora, en PHP, debería poder acceder a sus archivos:
// ie $_FILES['file-0']Aquí hay otra forma.
Suponiendo que su HTML es así:
<form id="theform"> <textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea> <!-- note the use of [] and multiple --> <input type="file" name="image[]" id="picture" multiple> <input name="update" value="Send" type="submit" class="update" id="update"> </form>Simplemente podrías hacer
$("#theform").submit(function(e){ // prevent the form from submitting e.preventDefault(); $.ajax({ url: 'post_reply.php', type: 'POST', contentType:false, processData: false, // pass the form in the FormData constructor to send all the data inside the form data: new FormData(this), success: function(result) { alert(result); }, error: function(xhr, result, errorThrown){ alert('Request failed.'); } }); $('#picture').val(''); $('#body').val(''); }); Debido a que usamos [] , estaría accediendo a los archivos como una matriz en PHP.
<?php print_r($_POST); print_r($_FILES['image']); // should be an array ie $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc ?>Más información: