0

its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>

<body>
<script type="text/javascript">
function fileChange()
{
    //FileList Objekt aus dem Input Element mit der ID "fileA"
    var fileList = document.getElementById("fileA").files;

    //File Objekt (erstes Element der FileList)
    var file = fileList[0];

    //File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
    if(!file) {
        return;
    }

    var x = substr(file.name, -4);
    document.getElementById("status").innerHTML = x;
    /*
    if (x != ".pdf") {
        document.getElementById("fileA").files = null;
        file = null;
        fileList = null;
        alert("Wrong Data");
        return;
    } */
    document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
    document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
    document.getElementById("progress").value = 0;
    document.getElementById("prozent").innerHTML = "0%";
}

var client = null;

function uploadFile()
{

    //Wieder unser File Objekt
    for(i=0;i < document.getElementById("fileA").files; i++) {
        var file = document.getElementById("fileA").files[i];
        //FormData Objekt erzeugen
        var formData = new FormData();
        //XMLHttpRequest Objekt erzeugen
        client = new XMLHttpRequest();

        var prog = document.getElementById("progress");

        if(!file)
            return;

        prog.value = 0;
        prog.max = 100;

        //Fügt dem formData Objekt unser File Objekt hinzu
        formData.append("datei", file);

        client.onerror = function(e) {
          alert("onError");
         };

        client.onload = function(e) {
            document.getElementById("prozent").innerHTML = "100%";
            prog.value = prog.max;
        };

        client.upload.onprogress = function(e) {
            var p = Math.round(100 / e.total * e.loaded);
            document.getElementById("progress").value = p;            
            document.getElementById("prozent").innerHTML = p + "%";
        };

        client.onabort = function(e) {
            alert("Upload abgebrochen");
        };

         client.open("POST", "upload.php");
        client.send(formData);
        }
}

}

function uploadAbort() {
    if(client instanceof XMLHttpRequest)
        //Briecht die aktuelle Übertragung ab
        client.abort();
}
</script>

<form action="" method="post" enctype="multipart/form-data">
    <input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
    <input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
    <input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
    <div id="status"></div>
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>

</div>
</body>
</html>

So this is my HTML Code and following up my upload.php:

<?php
if (isset($_FILES['datei']))
{
    move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>

My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
ndslr
  • 47
  • 2
  • 8

3 Answers3

1

There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:

The HTML

<!-- IMPORTANT:  FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
  <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>

Listing Multiple Files with JavaScript

//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');

//empty list for now...
while (list.hasChildNodes()) {
    list.removeChild(ul.firstChild);
}

//for every file...
for (var x = 0; x < input.files.length; x++) {
    //add to list
    var li = document.createElement('li');
    li.innerHTML = 'File ' + (x + 1) + ':  ' + input.files[x].name;
    list.append(li);
}

The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.

Receiving and Handling Files with PHP

if(count($_FILES['uploads']['filesToUpload'])) {
    foreach ($_FILES['uploads']['filesToUpload'] as $file) {

        //do your upload stuff here
        echo $file;

    }
}

PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.

Source

Demo

Bfcm
  • 2,686
  • 2
  • 27
  • 34
0

This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().

ajax_upload.js

Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().

function doUpload(fle_id, url_upld)
{
    var upldLimit = 2000000; // 2mb by default;

    if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
        alert('nothing to upload');
        return;
    }

    // put files to formData
    var tfSize = 0; // in bytes
    var fd = new FormData();
    $.each($('#'+fle_id)[0].files, function(i, file) {
        fd.append(i, file);
        tfSize = tfSize + file.size;
    });

    // you may check file size before sending data
    if(tfSize > upldLimit) {
        alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
        return;
    }

    // actual data transfer
    $.ajax({
        url: url_upld,
        cache: false,
        data: fd,
        type: 'POST',
        contentType : false,
        processData : false,
        success: function(data){
            alert(data);
        },
        error: function(jqXHR, textStatus, errorMessage) {
            alert(errorMessage);
        }
    });
}

upload_form.html

Let's use jquery to make things simple.

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
    $(function(){

        $('form').submit(function(e){
            if( e.preventDefault ) e.preventDefault(); // chrome/firefox
            else e.cancelBubble(); // IE

            // supply file input id and upload url
            doUpload( 'fle', $(this).attr('action') );

        });

    });
</script>
Upload
<form   action="ajax_upload.php"
        method="post"
        enctype="multipart/form-data"
        accept-charset="utf-8"
>
    <input type="file" id="fle" name="fle[]" multiple >
    <button type="submit">Upload</button>
</form>

ajax_upload.php

<?php

    if(count($_FILES) == 0) {
        echo 'Nothing uploaded.';
        exit;
    }

    $upldPath = 'E:/stack/upload/';
    foreach($_FILES as $file) {
        if ($file['error'] == UPLOAD_ERR_OK) {
            try {
                if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
                    // abort even if one file cannot be moved.
                    echo 'Cannot upload one of the files.';
                    exit;
                }
            }
            catch(Exception $e) {
                echo 'Cannot upload the files.';
                exit;
            }
        } else {
             // abort even if one file has error.
             echo 'Cannot upload one of the files.';
             exit;
        }
    }

    echo 'Upload successful!';

?>
duduwe
  • 888
  • 7
  • 16
0

Here is a simple approach to solving this issue.

This FormData append method works on IE 10 up and any other browser.

let files = []
let formData = new FormData
let filesInput = document.getElementById('files')

function prepareFiles() {
  files = filesInput.files
}

function uploadFiles() {
  // Arrange the files as form data to be sent to php
  files = Array.from(files)
  files.forEach(file => formData.append('files[]', file))

  // See all selected files
  console.log('Files')
  console.log(formData.getAll('files[]'))

  // Then send to php with jquery, axios e.t.c
  
  console.log('Server response')
  $.post('/pathtophpscript', formData, (response) => {
    console.log(response)
  }).catch(error => console.log(error))

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">