Home > Mobile >  Can't upload multiple files PHP
Can't upload multiple files PHP

Time:01-25

I have a problem. I want to be able to upload one or more files from html and then with ajax and php to save them on my server. If i just want to upload one file, it works fine, but if I want to upload more than one it doesn't work. The thing is, i have a table with 4 options and the last one is upload. But there is an ADD button under that, so when I click on that button another table (the same table) apperas, and there is where I have the problem. This is the HTML code part:

   <table id="myTable" >
              <tbody id="personalInfo">
                <tr>
                  <td >
                    <input type="text"  name="name0"
                      placeholder="<?php echo  $translate['name'][$lang]?>">
                  </td>
                  <td >
                    <input type="text"  name="surname0"
                    placeholder="<?php echo  $translate['surname'][$lang]?>">
                  </td>
                  <td >
                    <input type="text"  name="age0" autocomplete="off"
                    placeholder="2000" required />
                  </td>
                  <td >
                    <div >
                      <input type="file"  id="UploadFile" name="UploadFile0" accept="application/pdf" required />
                    </div>
                  </td>
                  
                  <td ><a ></a>
                  </td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <td colspan="5" style="text-align: left;">
                    <input type="button"  id="addRow"
                      value="<?php echo  $translate['add'][$lang]?>" />
                  </td>
                </tr>
                <tr>
                </tr>
              </tfoot>
            </table>

Okey and then I use JS to add another row when I click the ADD button. Everything works fine, but with the file I do this:

 var fileCounter = 0;  

      const fileSelector2 = document.getElementById('UploadFile');
      var file2;
      
      fileSelector2.addEventListener('change', (event) => {
        
        file2 = event.target.files[fileCounter];
        fileCounter  ;
      });

And then with JS i use ajax to send it a POST to php. The php part is this:

$name=$json->fullName ;

            $location = "../location/" .$name.$cont. ".pdf"; 

                        
            if (!move_uploaded_file($_FILES['file2']['tmp_name'], $location)) {
                echo json_encode(-1);
                exit();
            }

Like I said, when I just upload one file, it works fine, but with more than one file I don't know how to save t and use POST with multiple files.

CodePudding user response:

In order to upload multiple files using HTML, you'll need to make a few changes to your HTML code.

First, you'll need to change the input type for the file field from "file" to "file[]", like this:

<input type="file"  id="UploadFile" name="UploadFile[]" accept="application/pdf" required />

This tells the browser that you're allowing multiple files to be selected for upload.

In your JavaScript, you'll need to change the way you're handling the file select event. Instead of only getting the first file in the list, you'll need to loop through all the files that are selected and add them to an array, like this:

var files = [];

const fileSelector2 = document.getElementById('UploadFile');
fileSelector2.addEventListener('change', (event) => {
  files = event.target.files;
});

In the PHP code, you'll need to loop through the $_FILES array and move each file to the desired location:

foreach ($_FILES['UploadFile']['name'] as $i => $fileName) {
  $name = $json->fullName;
  $location = "../location/" . $name . $cont . ".pdf";
  if (!move_uploaded_file($_FILES['UploadFile']['tmp_name'][$i], $location)) {
    echo json_encode(-1);
    exit();
  }
}

It's important to note that with this approach, the file names will be the same, so you should change the file names on the server side or use a unique id to avoid overwriting previous files.

when sending the files to the server using AJAX, you'll need to use the FormData object to package up the files and send them with the request. Here's an example of how you can do this:

const formData = new FormData();
for (let i = 0; i < files.length; i  ) {
  formData.append("UploadFile[]", files[i]);
}

$.ajax({
    url: 'your url',
    data: formData,
    type: 'POST',
    contentType: false,
    processData: false,
    success: function (data) {
        console.log(data);
    }
});

It's important to set the contentType and processData options to false when using FormData. This tells jQuery not to try and process the data as a regular form submission and to leave it as the raw files.

CodePudding user response:

The following code allows you to upload multiple files..

HTML:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple>
    <input type="submit" value="Upload">
</form>

Javascript:

$(document).ready(function(){ 

    $('form').on('submit', function(e){

        e.preventDefault();

        var formData = new FormData($(this)[0]);

        $.ajax({

            url: 'upload.php', // point to server-side PHP script 
            dataType: 'text',  // what to expect back from the PHP script, if anything
            cache: false,
            contentType: false,
            processData: false,
            data: formData,                         
            type: 'post',

            success: function(response){

                alert(response); // display response from the PHP script, if any

            }

         });

    });                                             
});                                          

PHP (upload.php):

<?php 

    if (isset($_FILES['files'])) {

        $errors = array();

        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {

            $file_name = $_FILES['files']['name'][$key]; // get the file name of the uploaded file            

        }
    }
?> 

  • Related