Examples that use the package approach

Examples that use the single-package approach: upload files when the form is submitted

We will use the previous two examples as a basis for two further examples:

    1. one that uses only a file selector,
    2. one that uses drag and drop.

Package approach: uploading everything at once

Example using a file selector (<input type=”file”>)

This time, we add the files to an HTML5 FormData object before sending XHR2 Ajax requests to the server (one for each file + one for the rest of the form).  The uploads only start once the form is submitted.

You can try this example at JSBin, and look at the source code and comments for details.

Example 3 of file uploads

Example using drag and drop

Same behavior as example 3, but this time using drag and drop.

Try the example at JSBin and look at source code and comments.

Example 4: uses drag'n'drop of files

PHP code for the single-package examples (with and without drag and drop, the PHP is the same)

This code is given “as is”. The principle is the same as with the examples given in the previous section, except that this time we do not have to deal with a temporary “RecycleBin” directory.

  1. <?php
  2. if (isset($_POST[‘givenname’]) && isset($_POST[‘familyname’])) {
  3.     echo $_POST[‘givenname’] . ‘ ‘ . $_POST[‘familyname’] . ‘ try to upload
  4.          file(s).’;
  5. }
  6. $folderName = date(“m.d.Y”);
  7. if (!is_dir(‘upload/’.$folderName)) {
  8.     mkdir(‘upload/’.$folderName);
  9. }
  10. $fn = (isset($_SERVER[‘HTTP_X_FILENAME’]) ? $_SERVER[‘HTTP_X_FILENAME’] :
  11.                                             false);
  12. if ($fn)
  13. {
  14.     file_put_contents(‘upload/’ . $folderName . ‘/’ . $fn,     
  15.                       file_get_contents(‘php://input’));
  16.     echo “$fn uploaded”;
  17.     exit();
  18. }
  19. else {
  20.    if (isset($_FILES) && is_array($_FILES) && array_key_exists(‘formFiles’,
  21.                                               $_FILES)) {
  22.       $number_files_send = count($_FILES[‘formFiles’][‘name’]);
  23.       $dir = realpath(‘.’) . ‘/upload/’ . $folderName . ‘/’;
  24.       if ($number_files_send > 0) {
  25.          for ($i = 0; $i < $number_files_send; $i++) {
  26.             echo ‘<br/>Reception of : ‘ . $_FILES[‘formFiles’][‘name’][$i];
  27.             $copy = move_uploaded_file($_FILES[‘formFiles’][‘tmp_name’]
  28.                     [$i], $dir . $_FILES[‘formFiles’][‘name’][$i]);
  29.             if ($copy) {
  30.               echo ‘<br />File ‘ . $_FILES[‘formFiles’][‘name’][$i] .
  31.                    ‘ copy’;
  32.             }
  33.             else {
  34.               echo ‘<br />No file to upload’;
  35.             }
  36.         }
  37.      }
  38.    }
  39. }
  40. ?>

Leave a comment