【问题标题】:download file with php用php下载文件
【发布时间】:2014-01-31 20:52:45
【问题描述】:

我想创建一个链接以使用 php 从服务器计算机的根目录下载 excel 文件。所以我写了一个简单的代码如下,

   <?php

   header("Content-disposition: attachment;     filename=example.xls");

   header("Content-type: application/vnd.ms-excel");

   readfile("example.xls");

   ?>

然后可以下载它但是当我想打开它时,我收到错误消息说我下载的文件的格式与文件扩展名指定的格式不同。我也用 jpeg 文件尝试了同样的方法,但没有得到同样的错误,但是当我点击它时,它什么也没显示。有人能帮我吗?我不太擅长编程。提前谢谢你!

【问题讨论】:

  • 当我遇到这样的问题时,我通常会先注释掉header() 函数,这样我才能看到它实际上发送了正确的数据。您还可以将服务器上的 example.xls 与保存到您的工作站的 example.xls 进行比较,以确保它们相同。

标签: php file path format


【解决方案1】:

试试这个

    $file='example.xls';  $filesize=filesize($file);
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
    header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header("Content-Length: " . $filesize);
$fh = fopen("$file, "rb");

// output file
while(!feof($fh)) 
{
# output file without bandwidth limiting
    print(fread($fh, filesize($file))); 
}
fclose($fh);

【讨论】:

  • 我在我的旧网站中使用它来下载第 n 个文件
  • 感谢您的回复。我试过了,但它给出了错误“没有收到数据”。
  • 你保存代码并在同一台计算机上的浏览器上打开它吗?因为我想将代码保存在服务器计算机中(远程),然后从其他计算机下载。我认为问题在于。
  • @AlexButtner 在标题中使用 basename() 函数指定文件名,如上面的代码
  • @AlexButtner 我在旧的文件共享网站中使用了相同的代码。如果您提供正确的文件路径,它应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2015-06-04
  • 2017-07-19
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
相关资源
最近更新 更多