【问题标题】:File Upload via Ajax with PHP [closed]使用 PHP 通过 Ajax 上传文件 [关闭]
【发布时间】:2021-01-17 20:15:01
【问题描述】:

我正在尝试使用 XMLHttpRequest() 函数上传文件以运行 php 脚本。 这是HTML代码

<form enctype="multipart/form-data" action="testupload.php" method="POST">
<input type="text" class="form-control input-lg" name="image_text" id="filename">
<input type="hidden" name="MAX_FILE_SIZE" value="51200000000" />
Send this file: <input name="usrfile" type="file" />
<input type="button" value="Send File" onclick="uploadtest()"/>
</form>

这里是javascript代码

function uploadtest(){
    
        var file2 =document.getElementById("filename").value;

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
              
                
                }
        };                

        xmlhttp.open("GET", "testupload.php?fileID=" + file2 , true);
        xmlhttp.send();

    }

这是我的 PHP 脚本

<?php

/if(!empty($_FILES['usrfile'])){
//    print_r($_FILES);
   // echo "goda";
 //   // File upload configuration
    $targetDir = "C:/wamp64/www/CMS_TEST2/uploads/";
    $allowTypes = array('mp4', 'jpg', 'png', 'jpeg', 'gif');
    
    // $fileName = basename($_FILES['file']['name']);
    $fileName = $_GET["fileID"];
    //  $fileName = "MCCT0001";
    $temp = explode(".", $_FILES["usrfile"]["name"]);
    $newfilename = $fileName.".".end($temp);
    $targetFilePath = $targetDir.$newfilename;
    
    
    // Check whether file type is valid
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    if(in_array($fileType, $allowTypes)){
        // Upload file to the server
        if(move_uploaded_file($_FILES['usrfile']['tmp_name'], $targetFilePath)){
            echo "File is valid, and was successfully uploaded.\n";
        
            print_r($_FILES);
        }
    }
    
     
//}

?> 

如果我使用 PHP isset 表单提交调用 php 脚本。文件上传工作。但是当我使用 ajax $_FILES 调用 php 脚本时的问题返回空。你能帮我解决我在这里做错的事情吗

【问题讨论】:

  • 尝试使用 JSON 编码 echo json_encode( array("file"=&gt;$_FILES)) 发送响应并检查是否收到响应。
  • 你得到的是文件名而不是文件本身。这可能会帮助你。 stackoverflow.com/a/23981045/5900189
  • 您可以通过检查页面来检查您的 ajax 在 chrome 控制台上是否正常工作。
  • ajax 正在工作,因为我可以看到所有回显响应都在页面控制台中打印

标签: javascript php ajax file-upload


【解决方案1】:

第一个问题是您在 AJAX 请求中使用了GET 方法。 GET 请求不能有请求正文。更准确地说,客户端可以发送一个 GET 请求有一个主体,但服务器被实现为忽略它。 请注意,您在form 中使用POST 方法。

第二个问题是您实际上并未在 JavaScript 代码中包含文件数据。 MDN website上有一个例子:看看FormData是如何在POST请求中发送文件的

        function sendFile(file) {
            const uri = "/index.php";
            const xhr = new XMLHttpRequest();
            const fd = new FormData();
            
            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText); // handle response.
                }
            };
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }

作为旁注,对于这种操作,我建议查看 HTML5 File API,读取文件的字节,并将它们发送到服务器。您还可以分块字节以发出更多网络请求,以支持上传任何大小的文件。

【讨论】:

  • 我仍然无法得到这个工作函数uploadtest(){ const fileInput = document.querySelector("#fileInput"); console.log("ttest 函数"); const fd = new FormData(); var xmlhttp = 新的 XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; fd.append('file', fileInput); xmlhttp.open("POST", "testupload2.php", true); xmlhttp.send(fd); }
  • 我收到“usrfile”未定义的 php 错误
  • 无论如何,非常感谢您的解释我也从makitweb.com/how-to-upload-file-with-javascript-and-php得到了一个完整的示例代码
  • 我很高兴能帮上忙。我认为你得到“usrfile”是未定义的,因为你应该在 FormData 中配置这个名称,所以: fd.append('usrfile', file); - 我从 MDN 网站复制了示例,但没有更新它以匹配您在 PHP 代码中服务器端期望的字段名称
猜你喜欢
  • 1970-01-01
  • 2010-10-18
  • 2013-02-18
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 2010-11-12
相关资源
最近更新 更多