9

I have an existing html form which uploads a file to the server as soon as the user selects an image file.

I have done something like this.

//html code
<input type="file" id="photo" name="photo" accept="image/*" />
// the usual html stuff

document.getElementById('photo').addEventListener("change",uploadImage);
function uploadImage()
{
    var xhr = new XMLHttpRequest();

    xhr.open("POST","/upload.php",true);    
    xhr.setRequestHeader("Content-type","image");

    var file = document.getElementById('photo').files[0];
    if(file)
    {
        var formdata = new FormData();
        formdata.append("pic",file);
        xhr.send(formdata);
    }
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200)
    {
             //some code
    }
};
}

But in my php file, I can't access this uploaded file. The $_POST array seems to be empty. I did a print_r for $_POST and it gave Array(). What am I doing wrong?

4
  • 1
    You do know that file uploads are in $_FILES, and not $_POST, corrrect? Commented Dec 31, 2015 at 16:29
  • Yes that is empty too... Commented Dec 31, 2015 at 16:30
  • 1
    You shouldn't need to set content-type as XHR should automatically detect that you have appended a file and use multipart/form-data. And php does not understand content-type image either which is why you are not getting anything Commented Dec 31, 2015 at 16:33
  • Such a careless mistake on my part. You are right. Commented Dec 31, 2015 at 16:48

1 Answer 1

10

You are using FormData which works very much the same way a normal form does.

First of all, in PHP files will not be in $_POST but instead in $_FILES, see the documentation.

What that documentation does mention, along with the $_FILES buffer, is that you need to use the multipart/form-data encoding, any FormData transferred through an XMLHttpRequest will have this set by default, though you may want to check it if the $_FILES remain empty. You should remove the xhr.setRequestHeader("Content-type","image"); and let the XHR object handle it, of - if that doesn't work - add

xhr.setRequestHeader("Content-type","multipart/form-data");

There is a pretty nice example right here at stackoverflow

Sign up to request clarification or add additional context in comments.

1 Comment

You are absolutely right. I removed it and now I have something in my $_FILES .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.