2017-07-26 83 views
1

这里开始的是:PHP finding file where post INCLUDES portion of filename来自服务器的PHP从POST下载文件

我想完成这个问题。

基本上,现在我可以将变量发布到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"; 
    } 
    } 
?> 

我试图用在这里找到了答案:Download files from server php

但我不能完全确定w ^在这里我应该把标题,或者如果我需要使用它们。

如果有更好的方法来做到这一点,请指教我。

预先感谢您。

回答

0

我建议你的快速解决方案是:如果文件存在则返回文件路径,如果文件不存在则返回false。 之后在你的JS代码中你可以检查,如果你的“data”== false,你可以抛出一个错误“文件不存在”,如果它不是“false”,你可以调用document.location.href = data; - 将你的浏览器重定向到文件,它会下载

0

你为什么不干脆用下载属性:

<?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"); 
} 
     }); 
    });