0

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!

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

Comments

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.