如何使用纯香草javascript和php上传文件? [英] How to upload file using pure vanilla javascript and php?

查看:60
本文介绍了如何使用纯香草javascript和php上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an existing html form which uploads a file to the server as soon as the user selects an image file.

我已经做了类似的事情.

I have done something like this.

//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数组似乎为空.我为$_POST做了print_r,它给出了Array().我在做什么错了?

But in my php file, I can't access this uploaded file. The $_POST array seems to be empty. I did a print_r for $_POST and it gave Array(). What am I doing wrong?

推荐答案

您正在使用FormData,它的工作方式与普通表单非常相似.

You are using FormData which works very much the same way a normal form does.

首先,在PHP文件中将不在$_POST中,而是在$_FILES中,

First of all, in PHP files will not be in $_POST but instead in $_FILES, see the documentation.

该文档确实提到了与$_FILES缓冲区一起使用的是,您需要使用multipart/form-data编码,通过XMLHttpRequest传输的任何FormData都将默认情况下具有此设置,尽管您可能想要检查$_FILES是否为空. 您应该删除xhr.setRequestHeader("Content-type","image");并让XHR对象处理它-如果不起作用-添加

What that documentation does mention, along with the $_FILES buffer, is that you need to use the multipart/form-data encoding, any FormData transferred through an XMLHttpRequest will have this set by default, though you may want to check it if the $_FILES remain empty. You should remove the xhr.setRequestHeader("Content-type","image"); and let the XHR object handle it, of - if that doesn't work - add

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

有一个很好的例子就在stackoverflow

这篇关于如何使用纯香草javascript和php上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆