spkvn
spkvn

Reputation: 194

JS / PHP ajax posting Blob

I'm testing out AJAX file uploads, I want to eventually be able to do it with images, but right now I'm happy to get text files working. I'll put a snip of my code below.

JS

var blob //creates blob global variable.

//reads in blob to blob global var on change of file input. 
function readBlob(evt){

    var files = evt.target.files;
    if(!files.length){
        alert("no file");
        return;
    }

    var file = files[0];    
    var reader = new FileReader();

    reader.onloadend = function(evt){
        if (evt.target.readyState == FileReader.DONE){
            document.getElementById("jsReturnDiv").textContent = evt.target.result;
            blob = new Blob([evt.target.result], {type: 'text/plain'});
        }
    };

    reader.readAsBinaryString(file);
}


function post(){
    var i = 0;
    xhr.open("POST","what.php",true);
    xhr.setRequestHeader("content-type","text/plain");
    xhr.onreadystatechange = function(){
        if(xhr.status == 200 && xhr.readyState == 4){
            callback(xhr.responseText);
        }
        log(i,xhr.responseText);
        i++;
    }
    xhr.send(blob);
}

function callback(text){                                        //HUEHUEHUE
    document.getElementById("phpReturnDiv").innerHTML = text + "</br>___encoded</br>" + jsVarDump(blob) //+ "</br>___decoded</br>" + jsVarDump(decodeURIComponent(blob));
}

function log(index, text){
    console.log("index:"+index+"_______________________\n"+text);
}

PHP

<?php
var_dump($_POST);
?>

The problem that I get is that the output of the php is always:

array(0) { }

I was wondering if it was immediately obvious what I'm doing wrong. File is interpreted as a binary string and fed into a blob object, with content type text/plain, then POSTed as text/plain.

Should I be using a different content-type header in my XHR object? Am I handling the blob incorrectly?

Thanks!

Upvotes: 0

Views: 165

Answers (1)

Musa
Musa

Reputation: 97727

You'll have to read php://input to get data from a post with content type text/plain. $_POST is only populated with application/x-www-form-urlencoded and multipart/form-data

$text = file_get_contents('php://input');

Upvotes: 1

Related Questions