繁体   English   中英

通过ajax将表单文件发送到php

[英]send file of form to php via ajax

我想通过ajax将文件发送到php,我有下面的代码,但是当我运行它时,它表示未定义索引:thefile是什么问题? 的HTML

function postData(url){

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.onreadystatechange =  function(){

            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var res = xmlHttp.responseText;
                document.getElementById("upLoadName").textContent=res;

                }
                }

            var formData = new FormData();
            formData.append("thefile", document.getElementById('thefile').files[0]);

                xmlHttp.send(formData);

}

以及形式:

<form action="#" >
<input type="file" name="thefile" id="thefile"/>
<input type="button" name="Send"  value="send" onclick="postData('upLoad.php');"/>  </form>

的PHP

echo json_encode($_FILES["thefile"]["name"]) ;

这是针对您有多个文件的情况,但也应适用于一个文件:

var formData = new FormData();
    jQuery.each($('#thefile')[0].files, function(i, file) {
    formData.append('thefile-'+i, file);
});

现在可以在以下位置找到第一个文件:

$_FILES['thefile-0']

另外,请务必设置内容类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM