提交文件对象:非法调用

Posting file objects: illegal invocation

本文关键字:非法 调用 对象 文件 提交      更新时间:2023-09-26

我想张贴多个图像对象到testphp.php。但是控制台打印错误说非法调用。

I have try:

<script type="text/javascript" src="/script/googleapis.js"></script>

<input multiple type="file" id="myFile" size="50">
<div id="sub">submit</div>
<div id="testtest"></div>
<script>
$("#sub").click(function(){
    // get the file objects
    var files = $("#myFile")[0].files;
    for (var i = 0; i < files.length; i++){
    //test if the files[i] has the file objects
    console.log(files[i]);
    //post objects to another php file
    $.post("testphp.php", {img: files[i]}, function(result){
                                $("#testtest").html(result);
                            });
    }

})

你不能那样做。如果你想发布文件,你需要使用FormData .

我还建议一次上传所有文件,而不是一次上传一个。

要发布FormData,您需要使用$.ajax代替。

$("#sub").click(function(){
    // get the file objects
    var files = $("#myFile")[0].files,
        data = new FormData;
    for (var i = 0; i < files.length; i++){
        //test if the files[i] has the file objects
        console.log(files[i]);
        //post objects to another php file
        data.append('img[]', files[i]);
    }
    $.ajax({
        url: "testphp.php",
        type: "POST",
        data: data,
        contentType: false,
        processData: false,
        success: function(result){
            $("#testtest").html(result);
        }
    });
});

现在在PHP中,如果您要上传多个文件,您的$_FILES['img']['name'](和其他键)可能是数组。