【问题标题】:Undefined index: files when uploading using ajax and php未定义索引:使用 ajax 和 php 上传时的文件
【发布时间】:2020-03-08 23:14:51
【问题描述】:

我正在尝试创建一个上传图片的页面。当我点击upload.php时出现此错误

未定义索引:第 3 行 E:\My-Laptop\Wamp\www\image-upload\upload.php 中的文件

如果我这样做print_r($_FILES)我会得到一个空数组。

我不确定我哪里出错了。

这是我的代码。

index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <link href="css/styles.css" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div class="container" >
            <form action="" method="post" enctype="multipart/form-data">
            <input type="file" name="files[]" id="file" multiple>

            <!-- Drag and Drop container-->
            <div class="upload-area"  id="drop-zone">
                <h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
            </div>
            </form>
        </div>

        <script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
        <script src="js/main.js"></script>
    </body>
</html>

我的 main.js

$(document).ready(function(){
    var dropZone = document.getElementById('drop-zone');

    dropZone.ondrop = function(e){
        e.preventDefault();

        var transfer = e.dataTransfer.files;

            uploadImage(transfer);
    }

    dropZone.ondragover = function(e){
        return false;
    }

    dropZone.ondragleave = function(e){
        return false;
    }
});

function uploadImage(files){
    var dataString = 'files='+files;

    $.ajax({
        type: 'POST',
        url: 'upload.php',
        data: dataString,
        success: function(response){
            console.log(response);
        }
    });
}

我的上传.php

<?php

    print_r($_FILES['files']);

【问题讨论】:

标签: php jquery ajax


【解决方案1】:

希望对你有所帮助:

function uploadImage(files){

    var data = new FormData();
    $.each( files, function( key, value ){
       data.append( key, value );
    });

   $.ajax({
        type: 'POST',
        url: 'upload.php',
        data: data,
        success: function(response){
            console.log(response);
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    相关资源
    最近更新 更多