如何使用纯香草javascript和PHP上传文件?

时间:2015-12-31 16:25:22

标签: javascript php form-data

我有一个现有的html表单,一旦用户选择了一个图像文件,就会将文件上传到服务器。

我做过类似的事情。

//html code
<input type="file" id="photo" name="photo" accept="image/*" />
// the usual html stuff

document.getElementById('photo').addEventListener("change",uploadImage);
function uploadImage()
{
    var xhr = new XMLHttpRequest();

    xhr.open("POST","/upload.php",true);    
    xhr.setRequestHeader("Content-type","image");

    var file = document.getElementById('photo').files[0];
    if(file)
    {
        var formdata = new FormData();
        formdata.append("pic",file);
        xhr.send(formdata);
    }
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200)
    {
             //some code
    }
};
}

但在我的php文件中,我无法访问此上传的文件。 $_POST数组似乎是空的。我为print_r做了$_POST,它给了Array()。我做错了什么?

1 个答案:

答案 0 :(得分:4)

您使用的FormData与普通表单的工作方式非常相似。

首先,PHP文件不在$_POST中,而是在$_FILESsee the documentation中。

该文档提到的内容以及$_FILES缓冲区是您需要使用multipart/form-data编码,通过FormData传输的任何XMLHttpRequest都会默认情况下设置,但如果$_FILES保持为空,您可能需要检查它。 您应该删除xhr.setRequestHeader("Content-type","image");并让XHR对象处理它 - 如果这不起作用 - 添加

xhr.setRequestHeader("Content-type","multipart/form-data");

有一个很好的例子right here at stackoverflow