gpt4 book ai didi

php - 在 PHP 中使用 Header 作为下载链接

转载 作者:可可西里 更新时间:2023-10-31 22:07:42 25 4
gpt4 key购买 nike

所以我的下载链接出现了这个问题。基本上我以前创建下载链接的方法是只有一个带有 method='link' 的表单按钮和作为文件链接的操作。这适用于 firefox 和其他但不适用于 safari。出于某种原因,当用户尝试从 safari 下载文件(excel 文件)时,它只会在浏览器上显示一堆 ascii 字符(我猜它试图使用浏览器读取它?)。好吧,我正在寻找另一种解决方案,似乎使用 header 是解决问题的方法。所以现在我正在尝试使用 method='post' 和 action='download.php' 创建一个表单按钮,其中有一个带有文件链接的隐藏字段。看起来像这样

function showDownloadWithHeader($link){
echo "<form action='download.php' method='post' >";
echo "<input class='downloadButton' type='submit' value='Download Report'>";
echo "<input type='hidden' name='filename' value='$link'>";
echo "</form>";
}

在 download.php 中,我只想要求用户下载文件。

<?php
if($_POST['filename'] == '' || empty($_POST['filename'])){
exit;
}

$filename = $_POST['filename']; //the file is 2 folder down. e.g. data/stack/bla.xlsx
$file = $filename;
$extension = end(explode('.', $filename));
error_reporting(E_ALL);
ini_set("display_errors",1);
// echo $filename;
// echo "<br/>";
// echo $extension;
// echo filesize($filename);
// echo "<br/>";
switch($extension){
case 'xls':
$mimeType = 'application/vnd.ms-excel';
break;
case 'xlsx':
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
}
// echo $mimeType;
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
    flush();
readfile($filename);
exit;
?>

我在 php.net 上的 readfile() 函数下看到了这个解决方案,但它似乎对我不起作用。我在本地主机上执行此操作。

最佳答案

这样的东西很好用。

header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));

关于php - 在 PHP 中使用 Header 作为下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3479432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com