让客户端从服务器下载文件

时间:2014-08-14 09:06:44

标签: php file-io

我需要实现一个代码,我可以让客户端在Web服务器上下载一个或多个本地文件。

我有3个文件: file1.php file2.js file3.php ,包含以下代码。

file1.php

<select name="file_list" class="myclass" id="f_list" style="height:25px; width: 280px">

<?php
  foreach (new DirectoryIterator("$filesFolder") as $file)
  {
    if((htmlentities($file) !== ".") && (htmlentities($file) !== ".."))
    {
      echo "<option>" . htmlentities($file) . "</option>";
    }
  }
  ?>
  </select>

  <?php
  echo "<input type=\"button\" value=\" Download \" onClick=\"downloadFile()\"/>";
  ?>
file2.js

中的

function downloadFile()
{
  $("#activity").html("<img src=\"img.gif\" style=\"left: 590px;top: 74px;margin: auto;position: absolute;width: 32px;height: 32px;\" />");

    $("#content").load("file3.php",
    {
      filename: $("#f_list").val()
    });
}

file3.php

if(isset($_POST["filename"]))
{
  $filename = $_POST["filename"];
  /* testing string */
  echo $filesFolder.$filename;

  if(file_exists($filesFolder.$filename))
  {
    ob_start();
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename='.basename($filename));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filesFolder.$filename));
    readfile($filesFolder.$filename);
    ob_end_flush();
    exit;
  }
}

我从readfile function PHP manual获取了最后一个PHP代码,因为行为正是我需要的。但是当执行 file3.php 时,文件内容(二进制数据)将在屏幕上打印出来。

我认为我缺少实施某些功能但我不知道它可能是什么。 如何获得readfile PHP手册页的相同结果?

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

文件2:

您无法使用.load()或类似方法下载文件。

只需使用window.location.href = "file3.php?filename="+$("#f_list").val();

即可

文件3:

在致电header()之前,您无法输出任何内容。在第5行注释掉echo

在文件2中,我们使用GET而不是POST,将$_POST替换为$_GET

答案 1 :(得分:1)

也可以使用ajax请求页面,只需使用

window.location.href='/download/url';

如果所有标题都正确,它将打开下载对话框而不离开当前页面。

答案 2 :(得分:0)

一种方法是尝试在新的标签/窗口中打开文件:

function downloadFile()
{
    window.open("file3.php?filename=" + encodeURIComponent($("#f_list").val()));
}

因为PHP页面的结果包含指示内容是下载而不是页面的标题,所以浏览器实际上不会导航,而是提供下载框。请注意,此方法使用GET而非POST,因此您必须在file3.php中从$_POST更改为$_GET$_REQUEST。此外,请确保在标题结束前删除echo,否则无效。