Retrieve Uploaded Blob with PHP
11,037
The data from the blob can be read from php://input
, as in
<?php
var_dump(file_get_contents('php://input'));
If however you want to send multiple pieces of data with a form data object it would be like a normal multipart/form-data post. All string would be available through $_POST
and all blobs and file through $_FILES
.
function upload() {
var data = new FormData();
var oReq = new XMLHttpRequest();
oReq.open("POST", 'upload.php', true);
oReq.onload = function (oEvent) {
// Uploaded.
};
var blob = new Blob(['abc123'], {type: 'text/plain'});
data.append('file', blob);
oReq.send(data);
}
Author by
three3
Updated on July 31, 2022Comments
-
three3 almost 2 years
I have a script that is creating a blob and posting it to a PHP file. Here is my code:
HTML/Javascript:
<script type="text/javascript"> function upload() { var data = new FormData(); data.append('user', 'person'); var oReq = new XMLHttpRequest(); oReq.open("POST", 'upload.php', true); oReq.onload = function (oEvent) { // Uploaded. }; var blob = new Blob(['abc123'], {type: 'text/plain'}); oReq.send(blob); } </script> <button type="button" onclick="upload()">Click Me!</button>
PHP:
<?php var_dump($_POST); ?>
When I look at my developer console, I am not getting any $_POST data on my PHP page. I need to know how to retrieve the text file being posted to PHP script.
Any help is greatly appreciated!
-
three3 almost 10 yearsThank you for the code above. I know see the content of the file 'string(6) "abc123"' in the developer console. How would I go about being able to access the blob through the
$_FILES
array? I updated my javascript withoReq.setRequestHeader("Content-Type", "multipart/form-data");
this but it still does not allow me to access the blob through the$_FILES
array. Any suggestions? -
Musa almost 10 yearsYou'll have to use a FormData object and append the blob to it and pass the Formdata object to
XMLHttpRequest.send
. -
three3 almost 10 yearsI am great with PHP, but not with javascript. Do you mind updating your code in your answer to include the FormData method you mentioned?
-
three3 almost 10 yearsThank you so much! I can now access it! Last question. How would I know save this blob (meaning the actual .txt file) in a "texts" directory on my server? To be more clear, how to I convert this blob into an actual text file?
-
Musa almost 10 yearsTake a look at the php manual for file upload via post php.net/manual/en/features.file-upload.post-method.php
-
PYK over 2 yearsThe whole day looking for a simple answer like that ... Many thanks from NY