PHP - 使用 Javascript 和 PHP 上传多个文件

PHP - Uploading multiple files with Javascript and PHP

本文关键字:PHP 文件 使用 Javascript      更新时间:2023-09-26

又是我。我目前正在尝试为我的网站构建一个多文件上传器,但不知道如何获取/处理所有文件。我认为首先向您展示代码将是一个更好的解释:

<!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>

所以这是我的HTML代码和跟进我的上传.php:

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

我目前的问题是,我不知道如何实现多重上传,或者更好地说,如何上传所有文件。

互联网上有一些教程,您可以通过谷歌搜索"多文件上传"来简单地找到。无论如何,这是一个例子:

该目录

<!-- 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>

使用 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);
}

input.files 属性提供了一个文件数组,您可以检查其长度; 如果有长度,可以循环遍历每个文件并访问文件路径和名称。

使用 PHP 接收和处理文件

if(count($_FILES['uploads']['filesToUpload'])) {
    foreach ($_FILES['uploads']['filesToUpload'] as $file) {
        //do your upload stuff here
        echo $file;
    }
}

PHP 创建一个使用给定 INPUT 名称上传的文件数组。 此变量将始终是 PHP 中的数组。

演示

这是

使用 ajax 上传的。还有其他方法,例如使用iframe和jquery的$.load()

ajax_upload.js

嗯。。。FormData不是IE安全的。因此,您可能需要求助于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

让我们使用 jquery 让事情变得简单。

<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!';
?>

这是解决此问题的简单方法。

此 FormData 追加方法适用于 IE 10 up 和任何其他浏览器。

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()">