Home > Software engineering >  How to access the form data (blob data) that is sent from XMLHttprequest and store it to specific lo
How to access the form data (blob data) that is sent from XMLHttprequest and store it to specific lo

Time:04-11

I have convert a canvas element into blob data with the canvas.toBlob() function , into variable blob . Then I append it to the formdata

const formData = new FormData();
formData.append('my-file',blob,fileName);

I use XMLHttpRequest to send the formData to storeImage.php

var sendImage = new XMLHttpRequest();
var url ="https://192.168.x.x/storeImage.php";
sendImage.open("POST",url, true);
sendImage.send(formData);

Inside storeImage.php I have these lines of code to at least try to access the formData first

<?php
    var_dump($_POST['my-file'])
?>

So that I can store it as file later on .

But result from var_dump is as followed .

Warning: Undefined array key "my-file" in E:\xampp\htdocs\wasp_bee\storeImage.php on line 2
NULL

How can I at least access the posted formData in the php file , so I can finally proceed to save the blob data as file to the server (./img) using the file_put_contents function ?

thanks in advance :)

CodePudding user response:

Binary files are accessible by using the $_FILES array.

An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section.

The uploaded file can store at your address by using the move_uploaded_file function.

move_uploaded_file($_FILES['my-file']['tmp_name'], 'address to store file');

Checking file error, name, format, etc are very important please check them at the main reference.

https://www.php.net/manual/en/reserved.variables.files.php

https://www.php.net/manual/en/function.move-uploaded-file.php

  • Related