簡體   English   中英

從POST從服務器下載PHP文件

[英]PHP download file from server from POST

從這里開始: PHP查找文件,其中包含文件名的一部分

我試圖解決這個問題。

基本上,既然我現在能夠將變量發布到PHP進程,然后使用該進程在目錄中查找文件,那么現在我需要能夠下載該文件(如果存在)。

快速回顧一下,在用戶輸入航程號並且數據表返回航程列表之后,用戶單擊鏈接,這是我將在其中開始代碼的地方:

$('.voyageFileCall').on('click', function()
{
  var voyage = $(this).attr('data-voyage');
  $.post('fileDownload.php', {voyage:voyage}, function(data)
  {
    // here is where I need to where either display the file doesn't exist
    // or the file downloads
  });
});

進程“ fileDownload.php”如下所示:

<?php
  if($_POST['voyage'] == true)
  {
    $voyage = $_POST['voyage'];
    $files = scandir("backup/");
    if(count($files) > 0)
    {
      $fileFound = false;
      foreach($files as $file)
      {
        if((preg_match("/\b$voyage\b/", $file) === 1))
        {
          // I'm guessing the download process should happen here
          echo "File found: $file \n"; // <-- this is what I currently have
          $fileFound = true;
        }
      }
      if(!$fileFound) die("File $voyage doesn't exist");
    }
    else
    {
      echo "No files in backup folder";
    }
  }
?>

我嘗試使用此處找到的答案: 從服務器php下載文件

但是我不確定應該將標題放在哪里,或者是否需要使用它們。

我可以建議您的快速解決方案是:如果文件存在則返回文件的路徑,如果文件不存在則返回false。 之后,您可以在JS代碼中檢查,如果“ data” == false,則可以引發錯誤“ file不存在”,如果不是,則可以調用document.location.href =數據; -它將您的瀏覽器重定向到該文件,並將其下載

為什么不簡單地使用下載屬性:

<?php
  if($_POST['voyage'] == true)
  {
    $voyage = $_POST['voyage'];
    $files = scandir("backup/");
    if(count($files) > 0)
    {
      $fileFound = false;
      foreach($files as $file)
      {
        if((preg_match("/\b$voyage\b/", $file) === 1))
        {
          // I'm guessing the download process should happen here
          echo 'File found: <a href="' . $file . '" download>' . $file . '</a> \n'; // <-- this is what I currently have
          $fileFound = true;
        }
      }
      if(!$fileFound) die("File $voyage doesn't exist");
    }
    else
    {
      echo "No files in backup folder";
    }
  }
?>

如果您真的想使用JavasScript開始下載,請使用style="display:none;" <a>然后在JS中單擊它:

echo 'File found: <a id="myDownload" style="display:none;" href="' . $file . '" download>' . $file . '</a> \n';

並稱之為:

  $('.voyageFileCall').on('click', function()
    {
      var voyage = $(this).attr('data-voyage');
      $.post('fileDownload.php', {voyage:voyage}, function(data)
      {
if(document.getElementById("myDownload")){
document.getElementById("myDownload").click();
}else{
console.log("file does not exist");
}
      });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM