Upload several input files via Ajax

Asked

Viewed 159 times

0

Hello I need to upload files via ajax, where each event of clicking the input file, I already upload the corresponding file. I do not know how to do this dynastically, since what changes between a field and another is the name. It is how not to repeat the variables for each input name

Javascript file

  $('#btnEnviar').click(function () {
                 $.ajax({
                     url: upload.php, 
                     data: form,
                     processData: false,
                     contentType: false,
                     type: 'POST',
                     success: function (data) {
                         alert(data);
                     }
                 });
             });    

HTML file

<div class="panel-body">
    Foto 3x4
    <br />
    <input type="file" name="foto3x4" class="btn btn-primary btn-xs" value="Upload">
</div>
<div class="panel-body">
    Foto 16x9
    <br />
    <input type="file" name="foto16x9" class="btn btn-primary btn-xs" value="Upload">
</div>

1 answer

0

You need your form to have enctype="multipart/form-data"

Having this, to upload via ajax, you need to create a Formdata:

  var form = $("#id_do_seu_form");
  var formdata = false;
  if (window.FormData){
      formdata = new FormData(form[0]);
  }

 $.ajax({
        url: upload.php, 
        data: formdata ? formdata : form.serialize(),
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
              alert(data);
        }
 });

How not to repeat the variables for each input name?

In the name of your Voce input you can put name="foto[]"

in php do the following to read all:

foreach ($_FILES['foto'] as $arq){
   //rotina de upload
}
  • In the case of type are files, but how to identify which file is related to foto16x9 and which is related to foto3x4?

  • Then in this case I believe that you will have to have a field for each photo even...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.