【问题标题】:PHP script doesn't receive file I send to it with AJAX using JqueryPHP脚本没有收到我使用Jquery通过AJAX发送给它的文件
【发布时间】:2021-05-24 18:08:20
【问题描述】:

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

相关的 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 检查它是否收到了文件。如果它在那里,它会打印出“很好”,但当我点击按钮时,它总是打印出(控制台日志)“坏”。

【问题讨论】:

    标签: php jquery ajax file-upload


    【解决方案1】:

    为了使它工作,需要在您的客户端 JavaScript 中更改两件事。

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

       fd.append("file", file.files[0]);
      
    2. 如果没有给定参数,jQuery 的$.ajax() 方法将默认发送一个 GET 请求(jQuery docs)。根据RFC 7231,“GET 请求消息中的有效负载没有定义的语义”。底层的XMLHttpRequest API 会忽略 GET 请求的任何主体 (XHR spec)。相反,您可能希望发送适合上传文件的 POST 请求 (PHP docs)。确保按如下方式添加 HTTP 方法:

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

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

    【讨论】:

    • 完美运行!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多