【问题标题】:Creating and Downloading a file using PHP使用 PHP 创建和下载文件
【发布时间】:2012-10-05 05:26:16
【问题描述】:

当用户提交以下表单时,我正在尝试重写和下载 .txt 文件,但在最后一关时遇到了问题。

<form id="saveFile" action="index.php?download" method="POST" onsubmit="return false;">
    <input type="submit" name="backupFile" id="backupFile" value="Save a file" />
    <input type="hidden" name="textFile" id="textFile" />
</form>

按下提交按钮时,我正在运行一个 jQuery 函数,其中包含以下(简化的)代码 - 我已取出我实际保存的代码并将其替换为一个简单的字符串。这将设置“隐藏”输入类型,然后提交表单。

$("#textFile").val('This is the text I will be saving');
document.forms['saveJSON'].submit();

提交表单时,运行以下 PHP 代码:

<?php 
if (isset($_GET['download'])) {

    $textData = $_POST["textFile"];
    $newTextData = str_replace("\\","",$textData);
    $myFile = "php/data.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    fwrite($fh, $newTextData);
    fclose($fh);

    header("Cache-Control: public");
    header("Content-Description: File Download");
    header("Content-Disposition: attachment; filename='".basename($myFile)."'");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: binary");
    readfile($myFile);
}
?>

直到 fclose($fh);行代码实际上工作正常; .txt 文件已使用所需的新内容进行更新,并且文件已下载。但是,当我打开下载的文件时,它包含 .txt 文件文本以及来自网页 (index.php) 的大量内容。

例如,文件可能如下所示

“这是我要保存的文本

这是我网站的h1

接下来是我的其余内容”

有人知道是什么原因造成的吗?

【问题讨论】:

  • 你是这样输出的。如果你停止这样做,它就不会发生。如果您重定向(或链接)到只负责提供下载的脚本,您可以轻松绕过。

标签: php jquery forms download submit


【解决方案1】:

首先,正如 Harke 所说,你重定向(或链接)到一个只负责提供下载的脚本,你可以轻松地绕过

在读取文件之前清理输出缓冲区并在读取文件之后退出脚本

ob_clean();
    flush();
    readfile($file);
    exit;

【讨论】:

  • 谢谢!!添加这三行使其无需任何重定向即可工作! :)
  • 是的,它有效!因为它会清理缓冲区并退出脚本。第一条信息是给你额外的信息。不客气:)
猜你喜欢
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多