首页 > 解决方案 > .xlsx 下载后在 PhP 中刷新页面

问题描述

在我的网站上,如果用户选择下载文件,我将名为 $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
}

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

我应该补充一点,我知道最后的 exit() 会阻止 PhP 脚本执行,但如果你省略那行代码,.xlsx 文件将被损坏。我还应该补充一点,我尝试了替代 fopen($file)、fread($file)、fclose($file) 并且这也给了我一个损坏的 .xlsx 下载,这是其他人似乎遇到的问题,其他人证明了这一点Stack Overflow 上的帖子。

标签: phpxlsx

解决方案


我想我明白你的问题是什么。通过运行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 是一种服务器端语言,因此无法判断文件何时在客户端完成下载。


推荐阅读