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:
- one that uses only a file selector,
- 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 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.

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.
- <?php
- if (isset($_POST[‘givenname’]) && isset($_POST[‘familyname’])) {
- echo $_POST[‘givenname’] . ‘ ‘ . $_POST[‘familyname’] . ‘ try to upload
- file(s).’;
- }
- $folderName = date(“m.d.Y”);
- if (!is_dir(‘upload/’.$folderName)) {
- mkdir(‘upload/’.$folderName);
- }
- $fn = (isset($_SERVER[‘HTTP_X_FILENAME’]) ? $_SERVER[‘HTTP_X_FILENAME’] :
- false);
- if ($fn)
- {
- file_put_contents(‘upload/’ . $folderName . ‘/’ . $fn,
- file_get_contents(‘php://input’));
- echo “$fn uploaded”;
- exit();
- }
- else {
- if (isset($_FILES) && is_array($_FILES) && array_key_exists(‘formFiles’,
- $_FILES)) {
- $number_files_send = count($_FILES[‘formFiles’][‘name’]);
- $dir = realpath(‘.’) . ‘/upload/’ . $folderName . ‘/’;
- if ($number_files_send > 0) {
- for ($i = 0; $i < $number_files_send; $i++) {
- echo ‘<br/>Reception of : ‘ . $_FILES[‘formFiles’][‘name’][$i];
- $copy = move_uploaded_file($_FILES[‘formFiles’][‘tmp_name’]
- [$i], $dir . $_FILES[‘formFiles’][‘name’][$i]);
- if ($copy) {
- echo ‘<br />File ‘ . $_FILES[‘formFiles’][‘name’][$i] .
- ‘ copy’;
- }
- else {
- echo ‘<br />No file to upload’;
- }
- }
- }
- }
- }
- ?>