Search code examples
javascriptphpmysqlaxiosblob

Send blob from js form with axios, get it with php and insert it in mysql db


After searching for a while, I'm still stuck and I need help.

For a personnal project, I need a js form where information are asked and also a photo. A js script allows to select a part of the photo and converts the photo to correct size and extension (first cropper-js and after image-conversion). With this, I have a blob file.

      var params = new URLSearchParams();
      params.append("data1", document.data1);
      params.append("data2", document.data2);
      params.append("data3", document.data3);
      params.append("data4", document.data4);
      params.append("blob", blob);
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      axios.post(url_to_php_file, params, config).then((res) => {
        console.log(blob);
      }

In console.log, I can see my blob object (size change if I change photo) Blob {size: 49759, type: 'image/jpeg'}

With php, I insert in mysql db

    function fonctioninsert($table,$valeurs) {
        global $bdd;
        global $prefix_tables;
        $requete = 'INSERT INTO '.$prefix_tables.$table.'(';
        $i = 0;
        foreach ($valeurs as $key => $value) {
            if ($i != 0) {
                $requete .= ',';
            }
            $requete .= $key;
            $i++;
        }
        $i = 0;
        $requete .= ') VALUE (';
        foreach ($valeurs as $key => $value) {
            if ($i != 0) {
                $requete .= ',';
            }
            $requete .= "'".$value."'";
            $i++;
        }
        $requete .= ')';
        $req = $bdd->prepare($requete);
        $req->execute();
        //$req->closeCursor();
        return $req;
    }


            $table = "table1";
            unset($valeurs);
            $valeurs = array(
                "data1" => $_POST["data1"],
                "data2" => $_POST["data2"],
                "data3" => $_POST["data3"],
                "data4" => $_POST["data4"],
                "blob" => $_POST["blob"]
            );
            fonctioninsert($table,$valeurs);

The process inserts data in db but the blob column (LONGBLOB type) is still the same with 13 o. size even if I change photo. I tried with $_FILE but in this case, I have nothing in mysql blob column.

It's like php receive nothing and/or insert a empty blob in db.

Does anyone know where I'm faulty ?


Solution

  • In fact, the issue is with the append. Before the append, I have a blob file but after, I have a file then the PHP script receive an file and can't insert it in a mysql blob column. As I'm not able to convert the file to blob with php on my server, I finally chose to use file saving instead mysql and it's working well.