简体   繁体   中英

plain (no library) AJAX file upload

I'm taking a quick stab at a light weight file upload facility.

There's been quite a few answers on SO regarding using jQuery to upload a file to the server, which I want to avoid.

I'm looking at way to upload a file to the server for validation when the file has been selected using plain Javascript (no JS libraries)

Key questions are:
1. Why doesn't the AJAX call work?
2. Once the 'Upload' button has been pressed, I'd like to verify on Server end that file name is the same, if the same, do nothing, if different, stop current Server processing, and start anew - is it possible to do that in PHP?

Current state of source files are below: 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 file:

<?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);

?>

Use the FormData object from XMLHttpRequest level 2.

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

This way you can access the file from PHP doing

$_FILES['thefile'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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