普通(无库)AJAX文件上传

时间:2014-10-07 03:36:05

标签: javascript php ajax file-upload

我正在快速刺入轻量级文件上传工具。

关于使用jQuery将文件上传到服务器,有很多答案,我想避免使用。

当我使用普通的Javascript(没有JS库)选择文件时,我正在寻找将文件上传到服务器进行验证的方法

关键问题是:
1.为什么AJAX呼叫不起作用?
2.上传'上传'按钮已被按下,我想在服务器端验证文件名是否相同,如果相同,什么都不做,如果不同,停止当前服务器处理,并重新开始 - 是否可以在PHP中执行此操作?

源文件的当前状态如下: HTML:

<!DOCTYPE html>
<html lang="en">
<body>
<form id="upload_form" action="processPage.php" method="post">
    <input type="file" accept=".csv" id="input_file">
    <output id="file_upload"></output>
    <label id="status_message"></label>
    <br>
    <input type="button" id="upload_to_server" value="upload" onclick="uploadFile" >

</form>
 <script>
    // Send file to server for validation
    function handleFileSelect(e)
    {
        // file that was uploaded
        file = e.target.files[0];

        // create XMLHttpRequest object
        if (window.XMLHttpRequest)
        {
            request = new XMLHttpRequest();
        }
        else
        {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
        request.open("POST", "processPage.php", true);
        request.setRequestHeader("X_FILENAME", file.name);
        // Check status message
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var message;
                switch (request.status) {
                    case 200:
                         message = "File validated successfully.";
                         break;
                    case 406:
                         message = "Error: No file selected.";
                         break;
                    default:
                        message = "File validation failure, check file contents.";
                        break;
                }
                var container = document.getElementById('status_message');
                container.innerHTML = message;
            }
            else {
                alert( "Unexpected error:  " + this.statusText + ".\nPlease try again");
            }
        };
        request.send(file);

    }

    // Process file on server - send it again to server if file name changed
    function uploadFile()
    {

    }

    var output = document.getElementById('file_upload');
    if (output.addEventListener) {
        output.addEventListener('change', handleFileSelect, false);
    } else {
        output.attachEvent('change', handleFileSelect);
    }

    </script>
</body>
</html>

php文件:

<?php
    if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_SERVER['HTTP_X_FILENAME'])) {
        $response_code = 406;
    }
    else {
        // FIXME - how to distinguish between the POST from AJAX 'validate file' & 'upload file' call

        $response_code = 200;
    }
    header('X-PHP-Response-Code: '.$response_code, true, $response_code);

?>

1 个答案:

答案 0 :(得分:4)

使用XMLHttpRequest level 2中的FormData对象。

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

这样你可以从PHP访问文件

$_FILES['thefile'];