Reputation: 9
I don't understand. I have the following JavaScript function that sends a blob object to PHP side:
function createDownloadLink(blob,encoding) {
fetch('https://localhost:443/process.php', {method: "POST", body: blob}).then( (response) => response.json() ).then( (aidata) => {
textInputG.value = aidata.text;
} );
}
On PHP side I catch the blob with the following code and everything simply works:
<?php
$data = file_get_contents('php://input');
// PROCESSING HERE //
$reply = array('text' => $text);
echo json_encode($reply);
?>
Now the problem is that I need to send MORE THAN ONE OBJECT from the JavaScript side, so I tryed to modify the function using FormData, but on PHP side I'm unable to read the blob:
function createDownloadLink(blob,encoding) {
const formData = new FormData();
formData.append('blob', blob);
formData.append('text', text);
fetch('https://localhost:443/process.php', {method: "POST", body: formData}).then( (response) => response.json() ).then( (aidata) => {
textInputG.value = aidata.text;
} );
}
This is what in theory I would have expected to work, but it doesn't!
<?php
$blob_data = $_FILES['blob']; # THIS IS NOT READ CORRECTLY #
$text_data = $_POST['text']; # This works instead #
// PROCESSING HERE //
It seems that instead of the bytes of the blob, what I receive on PHP is the string "[object Blob]" inside the $_POST['blob'] array, and nothing inside the $_FILES['blob'] array.
What am I doing wrong, and how can I fix the issue?
I'm trying to get the JavaScript blob along with the text in FormData on the PHP side.
This question is NOT a duplicate of "How to convert Blob to File in JavaScript", NONE of the solutions posted there works for me.
The blob already works when attached directly to POST body in the fetch method, but DOES not work anymore if I try to encapsulate it in FormData object. Weather I transform it into a file or not, makes absolutely NO DIFFERENCE... is there a way to get the blob object transmitted correctly to the PHP processing page?
Upvotes: 0
Views: 77
Reputation: 46
Try adding these contentType & processData options, Here is an example
let data = new FormData()
for (var x = 0; x < files.length; x++){
data.append("file" + x, files[x]);
}
fetch(url, {
method: 'POST',
mode: 'cors',
contentType: false,
processData: false,
body: data
})
.then(parseResponse)
.then(resolve)
.catch(reject);
Upvotes: 1