PhP中的页面刷新后.xlsx下载



在我的网站上,如果用户选择下载文件,我会将名为$step的会话变量设置为"downloadEnd";我的PhP代码使用以下代码下载模板文件:

if ($step == "downloadEnd") {

$file = "Template.xlsx";
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename="" . basename($file) . """);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
exit();
$step = "nextStep"; // THIS IS THE LINE THAT DOES NOT EXECUTE
}
if ($step == "nextStep") {
// New Information Rendered to the User
}

除了第一行的最后一行不显示为"execute"之外,上面的代码是有效的。换句话说,下载完成后,我希望用户看到一个带有新文本的新页面,该文本位于单独的if语句中。。。如果($step="downloadStart"(。。。但它永远不会到达那里。我相信这是因为我需要以某种方式"欺骗"服务器,使其认为在文件下载后,有另一个用户从浏览器POST到服务器,以便PhP遍历所有"if"语句,并将新信息呈现给用户。我似乎找不到任何一种方法:(I(让PhP在文件下载完成后触发页面刷新;或者(ii(诱使服务器认为一旦文件完成就需要刷新页面。如有任何帮助,我们将不胜感激。

我应该补充一点,我知道末尾的exit((会阻止PhP脚本的执行,但如果您省略了那行代码,.xlsx文件将被损坏。我还应该补充一点,我尝试了替代fopen($file(、fread($file。

我想我明白你的问题是什么了。通过运行exit(),你可以告诉PHP停止它正在做的事情。尝试以下代码:

if ($step == "downloadEnd") {
$file = "Template.xlsx";
header('Content-Description: File Transfer');
header('Content-Type: ' . $mime);
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename="" . basename($file) . """);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($file);
$step = "nextStep"; // THIS IS THE LINE THAT DOES NOT EXECUTE
}
if ($step == "nextStep") {
// New Information Rendered to the User
}

此外,您可能需要查看JavaScript,以便在文档下载后刷新页面。

编辑

如果你想把它展示成一个";点击链接如果文件没有正确下载";页面将是然后以下应该工作:

if ($step == "downloadEnd") {
$fileURL = "https://example.com/path/to/Template.xlsx";
echo('<script>window.open("' . $fileURL . '", "_blank");</script>');
$step = "nextStep";
}
if ($step == "nextStep") {
// New Information Rendered to the User
}

您可以使用类似ob_end()ob_end_clean()的东西,但最好将新信息放在一个单独的页面上,并使用echo('<script>window.location.replace("new.php")</script>')将用户重定向到那里。希望有帮助!此外,PHP是一种服务器端语言,因此无法判断文件何时在客户端上完成下载。

最新更新