Send function parameters with fetch api

I want to save a generated blob pdf with a filename to the server using fetch api. I managed to save the pdf but how i can send the variable fileName.

JS code :

function uploadBlob (blob, fileName) { 
   fetch(`http://localhost/upload.php`, {
     method:"POST",
     body:blob
   }).then(response => console.log(response.text()))
}

upload.php :

<?php    
    $data = file_get_contents('php://input');
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/pdf/generatedpdfwithfilenanme.pdf", $data );
?>

Thanks in advance

30 thoughts on “Send function parameters with fetch api”

  1. Use a File constructor around the Blob to add a name to it. The File constructor is basically an extended Blob with some extra properties, like a name property.

    function uploadBlob (blob, fileName) {
      const file = new File(blob, fileName);
      fetch(`http://localhost/upload.php`, {
        method: "POST",
        body: file
      }).then(response => console.log(response.text()))
    }
    
    Reply
  2. am not sure about php but javascript side should be correct as i have experiance with it

    function uploadBlob (blob, fileName) { 
       fetch(`http://localhost/upload.php?fileName=${fileName}`, {
         method:"POST",
         body:blob
       }).then(response => console.log(response.text()))
    }
    

    and in php

    <?php    
        $fileName = $_GET["fileName"];
        $data = file_get_contents('php://input');
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/pdf/" . $fileName /*. ".pdf" */, $data );
    ?>
    

    edit

    i had a bug in code, accessing wrong url key, its now fixed

    Reply

Leave a Comment