gpt4 book ai didi

php - 使用浏览器提示下载文件

转载 作者:IT王子 更新时间:2023-10-28 23:45:29 27 4
gpt4 key购买 nike

我有一个 php/mysql 站点,我试图在其中下载逗号分隔文件 (CSV)。我创建的 csv 文件包含逗号分隔的数据(姓名、地址、城市、州)。我创建了 csv 文件,并将其放在站点的/downloads 目录中。到目前为止,一切都很好。我一直在网上找,我最常看到的触发浏览器下载提示的代码是:

$path = $_SERVER['DOCUMENT_ROOT'];
$exportfile = "emailclientaddresses.csv";
$fullpath = "downloads/" . $exportfile;
header("Content-type: text/plain");
header("Content-Length: ".filesize($exportfile));
header("Content-Disposition: attachment; filename=" . $fullpath);

$exportfile 是我的代码创建的 csv 文件。没关系。这是做什么的:

  1. $fullpath 以一种非常奇怪的格式显示在浏览器下载提示中:download_emailclientaddresses.csv
  2. 下载时,会下载当前网页或 csv 文件和当前网页的组合。

好的,我尝试了很多东西,但没有任何效果。因此,如果有人可以帮助我,我将不胜感激。谢谢。

埃德科恩

最佳答案

PHP documentation提供了一个很好的例子:

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>

编辑 (对评论的回应、解释)

header('Content-Description: File Transfer');

不在浏览器中显示,而是传输文件。

header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');

文件是二进制文件。
浏览器通常会下载二进制文件,除非它们可以显示它们。

header('Content-Disposition: attachment; filename='.basename($file));

使下载对话框显示正确的文件名。
注意:您可以使用任何文件名。

header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

文件不应被浏览器缓存。
在动态内容的情况下,缓存可能会导致问题。

header('Content-Length: ' . filesize($file));

向浏览器发送正确的文件大小,
否则浏览器无法估计传输时间。

ob_clean();
flush();

确保在下载开始之前将 header 发送到浏览器。

readfile($file);

将文件发送到浏览器。

exit;

完成:)

关于php - 使用浏览器提示下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11315951/

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