通过标题下载文件

时间:2012-03-29 06:31:43

标签: php

所有我需要帮助下载文件通过标题它工作正常,但问题是该文件放在一个文件夹中,我不明白如何为该特定文件提供路径。文件下载总是给我空文件。我的基本sanario是我点击链接(图像)下载一个名为(documents.php)的页面上的文件,该文件将我发送到另一个名为download.php.in的页面,该页面设置了用于下载所点击文件的标题,如

这是一个链接(document.php)

<a href="download.php?title=<?=$arr['title']?> "><img src="images/xl_icn.jpg" alt="" width="19" height="20" /></a>

这是标题(download.php)

header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');

header("Content-Disposition: attachment; filename='".$_GET['title']."'");

if(isset($_SESSION)){
  header('Location: documents.php');
}

并在下载后将其发送回documents.php页面,但我要下载的文件是文件夹上传/文件,我不知道如何下载上传/文件中的文件。

2 个答案:

答案 0 :(得分:0)

您无法从下载页面重定向。 download.php应该只做

echo $binary_file_contents;

并退出,它无法发送重定向标头。

您可以在iframe中打开它,这样您就不会真正离开documents.php页面

答案 1 :(得分:0)

您有一个良好的开端我会修改您的代码,使其更像以下内容:

$path = $_SERVER['DOCUMENT_ROOT']."/uploads/documents/";
$fullPath = $path.$_GET['title'];

if ($fd = fopen ($fullPath, "r")) {
  $fsize = filesize($fullPath);
  header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
  header("Content-Disposition: attachment; filename='".$_GET['title']."'");
  header("Content-length: $fsize");
  header("Cache-control: private");
  while(!feof($fd)) {
    $buffer = fread($fd, 2048);
    echo $buffer;
  }
}
fclose ($fd);

$ path你要更新什么文件夹 if语句用于执行所需的文件调用,并以缓冲区样式回显页面内容。

这可以进一步扩展为包含switch语句,具体取决于更改Content-type声明的扩展名。由于您将内容缓冲到页面,因此无法调用header("Location");。或者,由于缓冲,您将获得“由于页面内容已加载”而无法发送标题。

我建议在新窗口或iframe(包装在div中,可以隐藏)在页面上打开它。您也可以将它包含在document.php文件中,而不是调用单独的文件。