首页 > 解决方案 > 如何使用 filepond 插件、ajax 和 php,在服务器上未检测到文件名

问题描述

我正在尝试将文件上传到 xammp 服务器。我无法访问它上传的文件。我对此链接表示怀疑server: 'http://localhost/',因为当我将其更改为在服务器端处理数据的 PHP 文件的名称时,它可以工作。

但我还在表单上添加了另一个名为 username 的字段,请看下面的代码,我想将它们与 Ajax 结合在单个提交事件中,但我不知道这种组合。

  //initialize file pond with jquery plugin
  $('#file').filepond({
    allowMultiple: false,
    server: 'http://localhost/'
  });
  //ajax

$("form").on('submit', function(e) {
  $.ajax({
    url: 'send.php',
    type: 'POST',
    data: new FormData(this),
    dataType: 'JSON',
    contentType: false,
    cache: false,
    processData: false,
  }).done(function(data) {
    if (data.success == false) {
      if (data.errors.username) {
        $('#username').append('<span class="text-danger">' + data.errors.username + '</span>');
      }
      if (data.errors.file) {
        $('#file').append('<span class="text-danger">' + data.errors.file + '</span>');
      }
    }
  });
  
  e.preventDefault();
});

//my form field between form tag
<form method="POST" enctype="multipart/form-data"> 
   <input type="text" name="username" id="username">
   <input type="file" name="file" id="file">
</form>

//php code validate file and name
$errors = [];
if(empty($_FILES['username'])) {
    $errors['username'] = 'Enter your name!';
}
//other validation goes here...
if(empty($_FILES['file']['name'])) {
    $errors['file'] = 'upload file!';
}
//other validation goes here...
echo json_encode($errors);

编辑: 我注意到输入类型文件中的 name 属性不可用/被插件删除,并且每次加载页面时输入 ID 也会被覆盖,

//example the input look like where the id="filepond--browser-men6qus3m" change every time i load new file


<input class="filepond--browser" type="file" id="filepond--browser-men6qus3m" aria-controls="filepond--assistant-men6qus3m" aria-labelledby="filepond--drop-label-men6qus3m" accept="image/png">

因此,为什么我得到未定义的错字和未附加的文件

标签: javascriptphpjqueryajaxfilepond

解决方案


您将使用 Ajax 请求发送 FormData。您在这里提到的问题是您想要包含使用FilePond库附加的文件。这是我将 FilePond 文件附加到 FormData 的解决方案:

$(document).ready(function () {
    pond = FilePond.create(
        document.querySelector('#file'), {
            allowMultiple: true,
            instantUpload: false,
            allowProcess: false
        });

    $("#upload_form").submit(function (e) {
        e.preventDefault();
        var fd = new FormData(this);
        // append files array into the form data
        pondFiles = pond.getFiles();
        for (var i = 0; i < pondFiles.length; i++) {
            fd.append('file[]', pondFiles[i].file);
        }

        $.ajax({
                url: 'fileupload2.php',
                type: 'POST',
                data: fd,
                dataType: 'JSON',
                contentType: false,
                cache: false,
                processData: false,
                success: function (data) {
                    //    todo the logic
                    // remove the files from filepond, etc
                },
                error: function (data) {
                    //    todo the logic
                }
            }
        );
    });
})
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
    <script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
    <link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
    <script src="https://unpkg.com/filepond/dist/filepond.js"></script>

<form id="upload_form" method="POST" enctype="multipart/form-data">
    <input type="text" name="username" id="username">
    <input type="file" name="file" id="file" class="filepond">
    <input type="submit" value="Upload"/>
</form>

在你的 PHP 端,你需要得到这样的文件:

$errors = [];

if (empty($_POST["username"])) {
    $errors['username'] = 'Enter your name!';
}

// check if file is set and uploaded.
if (!isset($_FILES['file']) || $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
    $errors['file'] = 'upload file!';
} else {
    $filesNum = count($_FILES['file']['name']);
    // Looping all files
    for ($i = 0; $i < $filesNum; $i++) {
        // same the file
        move_uploaded_file($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i]);
    }
}

// Other validation goes here...
// Return the proper response to the client
// I'll leave this to you

请注意:

  • 我已禁用FilePond 以防止自动上传和处理instantUploadallowProcess
  • 您的 PHP 端需要更多验证,并且它应该向 Ajax 返回正确的响应。

推荐阅读