Reputation: 188
I'm trying to let users upload huge files ~1GB using PHP and HTML/JS. I know from past experiences that uploading files ~10mb also causes PHP to refuse the request.
Issue is, the request in my js gets sent, but I can't figure out how to send blobs through php. the post request is always empty
My javascript goes like this:
var xhttp = new XMLHttpRequest();
function doThing(){
var file = document.getElementById("file_upload").files[0];
var chunkSize = 1024 * 1024;
var fileSize = file.size;
var chunks = Math.ceil(file.size/chunkSize,chunkSize);
var chunk = 0;
console.log('file size..',fileSize);
console.log('chunks...',chunks);
sendFileSlice(file, chunkSize, chunk, chunks);
}
function sendFileSlice(file, chunkSize, chunk, chunks)
{
if(chunk <= chunks)
{
var offset = chunk*chunkSize;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
chunk++;
sendFileSlice(file, chunkSize, chunk, chunks);
}
};
xhttp.open("POST", "printchunks.php", true);
xhttp.send(file.slice(offset,offset+chunkSize));
}
}
and my php, just for test, goes like this:
<?php
//temporarily just put contents into a random file
file_put_contents(time()+rand(), print_r($_POST, true));
?>
I'm using Splitting a File into Chunks with Javascript this as an example for splitting, but i can't find AJAX using pure Javascript. I do NOT want JQuery, that's the last thing I need, I just want to send a blob to PHP so it can append it to the file. This seems to work in terms of splitting, it just doesn't have anything in the files produced
Upvotes: 3
Views: 2453
Reputation: 188
I forgot that I had to use
xhttp.setRequestHeader('Content-Type', 'application/octet-stream');
before sending to set the stream to be a blob. With this, I can now save the file using this PHP:
<?php
file_put_contents(time()+rand(), file_get_contents("php://input"));
?>
Of course this saves it into some random file, so if this helps anyone, please change the code to fit your needs
Upvotes: 2