4

I want to send a file to the server and process it there, then send a response. To send a file, I used the method of FormData(), everything seems fine, the file is sent, but it is impossible to parse with $_FILES + content is only visible through the php://input

  1. Why is the file is not visible from the $_FILES?
  2. How to parse?
  3. Does FormData() Works in all browsers?

My code:

HTML

<form id="myform">
    <input type="file" name="filename">
    <input type="button" name="button" value="Send">
</form>

JS

var form = document.forms.myform;
form.elements.button.onclick = function(){
    var file = form.elements.filename.files[0];
    if(file){
        img(file);
    }else{
        alert("Not file.");
    }
};
function img(file){
    var formdata = new FormData();
    formdata.append('file', file);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'img.php');
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    xhr.send(formdata);
    xhr.onreadystatechange = function(){
        if(xhr.readyState != 4) return;
        if(xhr.status != 200){
            alert("Status: " + xhr.status);
        }else{
            alert(xhr.responseText);
        }
    };
}

PHP

<?php
error_reporting(-1);
print_r($_FILES['file']['size']); // only example, doesn't work

$content = file_get_contents('php://input');
print_r($content); // it's work , result in the photo
?>

Photo

TotalHen
  • 41
  • 1
  • 4

1 Answers1

0

1. Why is the file is not visible from the $_FILES?

Because it is not necessary to use the encoding.

2. How to parse?

With global variable $_FILES

3. Does FormData() Works in all browsers?

No. Browser compatibility

TotalHen
  • 41
  • 1
  • 4