2

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.

1 Answer 1

3

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'];
2
  • 1
    Thank you! Yes, the content-type statement was the problem! (The other error was a typo that crept in as I was posting to SO.)
    – TobyRush
    Commented Nov 23, 2020 at 16:44
  • Glad I could help :)
    – Harshana
    Commented Nov 23, 2020 at 16:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.