Question

I'm trying to upload a file with AJAX. This is my first time ever using FormData.

On my client side script I just loop through the $_FILES and echo each, just for confirmation that they're being sent, and they're not. I checked the $_POST array too, but that is empty as well. The server-side script is being called though, just doesn't appear to be receiving any data from JavaScript.

Here is my code, what am I doing wrong?

The JS

var client = new XMLHttpRequest();
function upload(){
    var file = document.getElementById("uploadfile");
    var formData = new FormData();
    formData.append("upload", file.files[0]);
    client.open("post", "/orl_ajax_uploader.php", true);
    client.setRequestHeader("Content-Type", "multipart/form-data");
    client.send(formData);
    return false;
}
client.onreadystatechange = function(){
    if (client.readyState == 4 && client.status == 200){
        alert(client.response);
    }
}

The HTML

<form action="orl_ftp.php" method="POST" enctype="multipart/form-data" onsubmit="return upload()">
    <table>
       <tr>
        <td>Choose File: </td>
        <td><input type="file" name="file" id="uploadfile" multiple /></td>
       </tr>
       <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="Submit" value="Process"></td>
       </tr>
    </table>
</form>

The PHP (for testing only)

$str = "POST PARAMS // ";
foreach($_POST as $k=>$v){
    $str .= $k."=".$v." :: ";
}
$str .= "FILES PARAMS // ";
foreach($_FILES as $k=>$v){
    $str .= $k."=".$v." :: ";
}
$str .= "GET PARAMS // ";
foreach($_GET as $k=>$v){
    $str .= $k."=".$v." :: ";
}
$str .= '"'.$_FILES['upload'].'"';
echo $str;

When I hit submit PHP sends back this string every time: POST PARAMS // FILES PARAMS // GET PARAMS // "" in addition to an undefined index error for trying to call $_FILES['upload'] ..which should be there, but isn't..

EDIT It's being sent..

Était-ce utile?

La solution

Using client.setRequestHeader("Content-Type", "multipart/form-data"); to set the Content-Type should not be used with uploading files/form data. The browser handles the generation of the Content-Type value, using boundaries and things internal to the request that we don't need to worry about. Not manually setting that request header should allow the browser to correctly include the file in the request and make it available to the server correctly.

Once this is changed, you should be able to access $_FILES["upload"], which is an associative array of attributes. If you need to get the actual contents, use something like file_get_contents($_FILES["upload"]["tmp_name"]), otherwise you can get information about the file, like its name, type, etc.


References:

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top