Ajax上传文件

时间:2015-06-06 14:05:52

标签: javascript php ajax

我正在测试使用Ajax和PHP上传文件。上面的代码成功而没有上传文件原因?

{   

    <form method="post"  enctype="multipart/form-data">
        <input id='files' type='file'>
    </form>
    <script>

        document.getElementById('files').addEventListener('change', function (e) {
            var file = this.files[0];
            console.log(file);
            var xhr = new XMLHttpRequest();
            xhr.file = file; // not necessary if you create scopes like this
            xhr.addEventListener('progress', function (e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;

            }, false);
            if (xhr.upload) {
                xhr.upload.onprogress = function (e) {
                    var done = e.position || e.loaded, total = e.totalSize || e.total;

            }
            xhr.onreadystatechange = function (e) {
                if (4 == this.readyState) {
                    console.log(['xhr upload complete', e]);
                }
            };
            xhr.open('post', 'arxeia', true);
            xhr.send(file);
        }, false);
    </script>


</body>}

你应该附上一个帖子处理程序吗?

1 个答案:

答案 0 :(得分:0)

您应该使用FormData发送文件

document.getElementById('files').addEventListener('change', function (e) {
    var file = this.files[0];
    console.log(file);
    var xhr = new XMLHttpRequest();
    var fd = new FormData();
    fd.append("file", file);

    xhr.addEventListener('progress', function (e) {
        var done = e.position || e.loaded, total = e.totalSize || e.total;
    }, false);
    if (xhr.upload) {
        xhr.upload.onprogress = function (e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
    }
    xhr.onreadystatechange = function (e) {
        if (4 == this.readyState) {
            console.log(['xhr upload complete', e]);
        }
    };
    xhr.open('post', 'arxeia', true);
    xhr.send(fd);
}, false);

然后,您将能够使用$_FILES["file"]

在服务器上获取该文件