【问题标题】:Why is form.append not appending multiple files? [duplicate]为什么 form.append 不附加多个文件? [复制]
【发布时间】:2020-06-09 23:15:30
【问题描述】:
<html>
<script src = "/jquery.js"></script>
    <form>
        Image here:<br>
        <input type = "file" id = "image" multiple><br>
        <input type = "button" id = "submit" value = "submit">
    </form>
</html>

<script>

$("#submit").click(function(){
    var form = new FormData();
    var filescount = $("#image")[0].files.length;

    for (var i = 0;i<=(filescount-1);i++){
        form.append( "finalform" , $("#image")[0].files[i]  );
    }

    $.post({
        url:"/test.php",
        processData: false,
        contentType: false,
        data:form,
        success:function(data){
            alert(data);
        }
    });


});
</script>
<?php
var_dump($_FILES);
?>

我的 JS 正在尝试使用 .files.length 从 $("#image")[0] 输入中选择文件的数量。我已经提醒了这个值,它正在计算我选择的正确文件数。

然后使用 for 循环,使用上面的计数作为索引,执行 form.append("finalform" , $("#image")[0].files[i])

但是,当我将它发送到 PHP 和 var_dump[$_FILES](在 JS 中被提醒)时,它只显示最后选择的图像。例如,如果我选择了 10 张图片,files.length 计数为 10。但是当 var_dump 被警告时,它只显示最后选择的文件,即文件 10.png。

知道为什么我的表单数据似乎没有通过其他 9 张图片发送吗?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    为了让 php 能够将您的 $_FILES 字段作为数组读取,您需要在其名称末尾附加 "[]"

    form.append( "finalform[]" , $("#image")[0].files[i]  );
    

    php docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-17
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 2019-11-22
      • 2012-10-17
      相关资源
      最近更新 更多