Javascript formData 数组返回空

我的 AJAX formData 对象有问题。如果在输入中选择一个文件并使用 AJAX 发送该文件,则数组为空。我希望有人能帮助我解决这个问题。下面是我的代码


HTML 和 JavaScript


    <form method="post" id="quoteform">

        <input type="file" name="uploadfile" id="quote"/>

        <input type="submit" value="upload"/>

    </form>

    <script type="text/javascript">

    document.getElementById("quoteform").addEventListener("submit", function(){

        var files           = document.getElementById("quote").files;

        var formData        = new FormData();

        

        for (var i = 0; i < files.length; i++) {

            var file = files[i]

            formData.append('files[]', file);

        }



        var xhttp           = new XMLHttpRequest();

        xhttp.open("POST", "linktophpfile.php", true);

        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        xhttp.send('upload='+formData);

        xhttp.onreadystatechange = function() {

            if (this.readyState == 4 && this.status == 200) {

                alert(this.responseText);

            }

        }

        event.preventDefault();

    });

    </script>

PHP


<?php

if(isset($_POST['upload'])){

    print_r($_FILES);

}

?>

PHP 文件返回 Array ( )


30秒到达战场
浏览 89回答 1
1回答

HUWWW

当您上传文件时,您将无法使用,application/x-www-form-urlencoded您必须使用multipart/form-data你不应该将字符串与 formData 混合,send('upload='+formData)它只会导致你上传等于upload=[Object object]您应该只发送 formData 并让 XHR 或 Fetch 自动为您处理内容类型。如果您想要一个数组,那么我想您也想要该属性mulitple?为了更好的衡量,你总是可以添加required和accept="image/*, .txt"如果您只使用接受表单元素的第一个构造函数参数,则无需手动将所有文件添加到表单数据中,表单中的所有内容都将被添加<form method="POST" action="https://httpbin.org/post" id="quoteform" encoding="multipart/form-data">&nbsp; <input multiple type="file" name="files[]" id="quote" required />&nbsp; <input type="submit" value="upload"/></form><script>// html (xml) should mark the settings, behavior as it mostly always have done// in all years way back and the js should provide enhancement and// be more generally written to enhance the site (if js where// to be turned off - most unlikely, I for once have it disabled in my phone)// static sites works better without ads + annoying cookie popups// it's a good thing Brave have quick toggle to enable scrips for js-only pagesfunction ajaxify (evt) {&nbsp; evt.preventDefault()&nbsp; var form = evt.target&nbsp; var formData = new FormData(form)&nbsp; fetch(form.action, {&nbsp; &nbsp; method: form.method,&nbsp; &nbsp; body: formData&nbsp; }).then(res => res.text()).then(alert)}document.getElementById("quoteform").addEventListener("submit", ajaxify)</script>
打开App,查看更多内容
随时随地看视频慕课网APP