【问题标题】:Send Multiple Files to PHP with Jquery and Fetch使用 Jquery 和 Fetch 将多个文件发送到 PHP
【发布时间】:2020-07-16 21:07:34
【问题描述】:

我正在使用 Jquery 构建一个 HTML 表单,以将数据发送到 PHP 后端。它应该允许多个附件,然后通过fetch 发送。我收到$_POST 很好,但$_FILES 只包含最后选择的文件。

我知道这是因为 multiple 属性会在每次打开新的文件选择器窗口时重置,但我会在每个文件被选中时保存它。为了解决这个问题,我试图捕获 JS 数组中的每个文件,在将数组发布到服务器之前将其附加到 FormData

$(document).ready(function(e){
    // Add input files to array
    $('#inputId').on('change', function(e) {
        fileList.push(fileName[0]);
    });

    // Form submission
    $("#formId").on('submit', function(e){
        e.preventDefault();
        formData = new FormData(this);
        formData.append(fileList);
        url = '../php/submit.php';
        fetch(url, {method: 'POST', body: formData})
            .then(function(response) {
                return response.text();
            })
            .then(function(body){
                console.log(body);
            });
    });
});
<form id="formId" enctype="multipart/form-data" method="POST">
  <div class="ds-row ds-file-upload-container ds-mar-b-2">
    <div class="ds-col-xs-12 ds-col-md-6">
      <label for="inputId" class="ds-button">Choose a file
        <input type="file" class="ds-file-upload" name="upload[]" id="inputId" multiple="multiple">
      </label>
    </div>
  </div>
</form>

截至目前,当点击submit 按钮时,表单没有提交任何内容。如果我注释掉#inputId onchange 事件,它可以工作,但当然,它没有包含在FormData 中的所有文件。

【问题讨论】:

  • 这能回答你的问题吗? Does fetch support multiple file upload natively?
  • FormDataInstance.append()使用不当。
  • “我知道这是因为每次打开新的文件选择器窗口时多重属性都会重置” - 你在说什么……?仅formData = new FormData(this); 就足以发送所有当前通过输入字段选择的文件,不需要手动附加任何内容。
  • @CBroe - 这种方法对我不起作用。每次我尝试向upload[] 添加第二个文件时,它只保留最后一个选择的文件。第一个文件消失了。仍然不知道为什么。

标签: javascript php html jquery


【解决方案1】:

这是为您提供的工作代码并经过测试。

formData append 有一些问题。您没有为您的文件执行任何 forEach 操作,因此当您发送获取请求时,您 formData 只会获取最后一个文件。

要存储多个文件,您需要一个空数组,我将其命名为 filesToUpload

此数组将存储您将在更改功能中选择的所有文件。

一旦数组包含您要上传的所有文件。在表单提交函数中,您将遍历该 filesToUpload 数组并将其所有数据附加到 formData 并通过获取请求发送。

在后端PHP 一侧,当您var_dump($_POST)var_dump($_FILES) 时,您将在那里看到所有这些文件。

工作小提琴演示: https://jsfiddle.net/woft6grd/

在演示中,当您使用开发工具 -> 网络时,您将在表单提交中看到您的请求将包含您通过输入上传的所有文件。

jQuery

$(document).ready(function() {

  // Add input files to array
  var filesToUpload = []

  //On Change loop through all file and push to array[]
  $('#inputId').on('change', function(e) {
    for (var i = 0; i < this.files.length; i++) {
      filesToUpload.push(this.files[i]);
    }
  });

  // Form submission
  $("#formId").on('submit', function(e) {
    e.preventDefault();

    //Store form Data
    var formData = new FormData()
    //Loop through array of file and append form Data
    for (var i = 0; i < filesToUpload.length; i++) {
      var file = filesToUpload[i]
      formData.append("uploaded_files[]", file);
    }

    //Fetch Request
    url = '../php/submit.php';
    fetch(url, {
        method: 'POST',
        body: formData
      })
      .then(function(response) {
        return response.text();
      })
      .then(function(body) {
        console.log(body);
      });
  })
});

HTML

<form id="formId" enctype="multipart/form-data" method="POST">
  <div class="ds-row ds-file-upload-container ds-mar-b-2">
    <div class="ds-col-xs-12 ds-col-md-6">
      <label for="inputId" class="ds-button">Choose a file
        <input type="file" class="ds-file-upload" name="upload[]" id="inputId" multiple="multiple" required>
      </label>
    </div>
  </div>
  <input type="submit" value="Upload" />
</form>

我还为每个代码行添加了 cmets 以突出显示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-11
    • 2021-12-11
    • 2022-01-16
    • 1970-01-01
    • 2011-06-12
    • 2018-08-18
    • 2013-08-23
    • 2023-03-16
    相关资源
    最近更新 更多