PHP 脚本没有收到我用 AJAX 使用 Jquery 发送给它的文件

PHP script doesn't receive file I send to it with AJAX using Jquery

我已经到处寻找解决方案了。人们都这样做,但它对我不起作用。

相关HTML:

<input type="file" name="file" id="file">
<button type="submit" id="submit" name="import">Import</button>

相关Jquery:

$(document).ready(function(){
                $("button").click(function(){

                    var fd = new FormData();
                    fd.append("file", file);
                    alert(fd.get("file"));

                    $.ajax({
                        //URL of the PHP file
                        url: "readFile.php",

                        //fd will be send
                        data:fd,

                        //json is the type that should be returned
                        dataType: "json",

                        //To prevent processing
                        cache:false,
                        contentType: false,
                        processData: false,

                        //when successful
                        success: function( data ) {
                            console.log(data);
                        }
                    });
                });
            });

最后,我写的 PHP 来查找错误:(名为 readFile.php)

<?php
if(isset($_FILES["file"]["name"])){
    echo json_encode("great");
}else {
    echo json_encode("bad");
}
?>

此代码有效,除了 PHP 应该收到文件的部分。

那个PHP检查它是否收到了文件。如果它在那里,它会打印出“很好”,但当我单击按钮时,它总是打印出(控制台日志)“坏”。

您的客户端有两处需要更改 JavaScript 才能正常工作。

  1. file 变量当前包含对 HTMLInputElement 的引用,而不是所选二进制文件。 file 类型的元素提供 files 属性 (MDN docs),其中包含选择上传的文件列表。要上传(单个)选定的元素,请像这样检索第一个元素:

     fd.append("file", file.files[0]);
    
  2. 如果没有给出参数,jQuery的$.ajax()方法将默认发送一个GET请求(jQuery docs). Per RFC 7231, a “payload within a GET request message has no defined semantics”. The underlying XMLHttpRequest API ignores any body for GET requests (XHR spec). Instead, you may want to send a POST request which is suitable for uploading files (PHP docs)。确保按如下方式添加 HTTP 方法:

     $.ajax({
       // existing configuration
       method: 'POST'
     });
    

应该是这个!另请注意,不需要设置 cache 属性,因为 POST 请求无论如何都不会被缓存。