Search code examples
javascriptphpajaxxmlhttprequestform-data

How do I upload a file using FormData and XmlHTTPRequest?


I'm trying to send a file from a web page to a php script using FormData, and the file isn't showing up in the $_FILES variable in the PHP page. Not sure if my error is on the JS side or the PHP side, or if I'm misunderstanding something deeper about the process.

Here's my code:

function uploadFile() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                console.log('success');
            } else {
                console.log('error');
            }
        }
    };
    xhr.open('POST','php/parsefile.php',true);
    xhr.setRequestHeader("Content-Type","multipart/form-data");
    var formData = new FormData();
    formData.append("myfile", document.querySelector('#fileInput').files[0]);
    xhr.send(formData);
}
<input type="file" id="fileInput">
<button onclick="uploadFile();">Upload</button>

Here's parsefile.php:

 <?php

 echo("Error: " . $_FILES["myfile"]['error'] . "\n");
 echo("Name: " . $_FILES['file']['name'] . "\n");

When I upload a simple, small (64 bytes) text file, the console reads success, but the response from the server is just this:

 Error: 
 Name: 

What am I missing here? Thanks for any help anyone can provide.


Solution

  • I found two issues in your code:

    1. In JavaScript code, you explicitly defined the "Content-Type" as "multipart/form-data". JS automatically gets the content type when you make the XHR Request.
    2. In the 4th line of your PHP code, the key of the $_FILE is "file". You need to change it to "myfile", in order to make it work.

    You can check my edited code below:

    JS Code:

    function uploadFile() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    console.log('success');
                } else {
                    console.log('error');
                }
            }
        };
        xhr.open('POST','php/parsefile.php',true);
        var formData = new FormData();
        formData.append("myfile", document.querySelector('#fileInput').files[0]);
        xhr.send(formData);
    }
    

    PHP Code:

    <?php
    echo "Name: ". $_FILES['myfile']['name'];
    echo "Error: ".$_FILES['myfile']['error'];