【问题标题】:Send function parameters with fetch api使用 fetch api 发送函数参数
【发布时间】:2021-05-17 16:05:52
【问题描述】:

我想使用 fetch api 将生成的带有文件名的 blob pdf 保存到服务器。我设法保存了 pdf,但我如何发送变量 fileName。

JS 代码:

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

上传.php:

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

提前致谢

【问题讨论】:

    标签: javascript php post fetch blob


    【解决方案1】:

    Blob 周围使用File 构造函数为其添加名称。 File 构造函数基本上是一个扩展的Blob,带有一些额外的属性,比如name 属性。

    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()))
    }
    

    【讨论】:

      【解决方案2】:

      我不确定php,但javascript方面应该是正确的,因为我有它的经验

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

      在php中

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

      编辑

      我的代码中有一个错误,访问了错误的 url 键,现在已修复

      【讨论】:

      • 除非文件名包含不能成为 URI 一部分的字符。你需要encodeURIComponent。此外,在 POST 中同时包含 GET 和 POST 参数有点不确定。 :-)
      • @levy - 同样,以上内容需要对文件名进行正确的 URI 编码:...?fileName=${encodeURIComponent(fileName)}
      猜你喜欢
      • 2018-10-08
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      相关资源
      最近更新 更多