强制下载文件损坏的标头错误吗?
if($_POST['mode']=="save") {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/mcboeking/";
$path = $root.$path;
$file_path = $_POST['path'];
$file = $path.$file_path;
if(!file_exists($file)) {
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
readfile($file);}}
当我下载文件并打开它时,我收到一条错误消息。当我尝试打开 .doc 文件时,收到消息:文件结构无效。 当我尝试打开 .jpg 文件时:无法打开该文件。它可能已损坏或预览无法识别的文件格式。
但是当我下载 PDF 文件时,它们打开没有任何问题。
有人可以帮助我吗?
PS我尝试了不同的标题,包括: header('内容类型:应用程序/八位字节流');
if($_POST['mode']=="save") {
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/mcboeking/";
$path = $root.$path;
$file_path = $_POST['path'];
$file = $path.$file_path;
if(!file_exists($file)) {
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
readfile($file);}}
As soon as I download the file and open it I get an error message. When i try to open a .doc file I get the message: file structure is invalid.
And when i try to open a .jpg file: This file can not be opened. It may be corrupt or a file format that Preview does not recognize.
But when I download PDF files, they open without any problem.
Can someone help me?
P.s. i tried different headers including :
header('Content-Type: application/octet-stream');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的标题与实际内容无关,因此问题是实际内容有问题。
另外,您确实不应该尝试通过更改 Content-Type 标头来强制下载。让它保持它应该的样子。让客户决定如何处理它。
Your headers have no bearing on the actual content, so the issue is that there is something wrong with the actual content.
Also, you really shouldn't try to force a download by changing the Content-Type header. Leave it what it is supposed to be. Let the client decide what to do with it.
确保除了
readfile()
数据之外不输出任何内容:确保 PHP 代码在 PHP 文件的第一个符号处以开头,并且文件末尾的结束
?>
之后没有任何符号,例如空格或换行符(或完全删除?>
)。Make sure you don't output anything but the
readfile()
data: ensure that PHP code begins with<?
at the very first symbol of the PHP file, and that there are no symbols after the closing?>
at the end of file, like a space or a newline (or remove the?>
altogether).在记事本中打开 PHP 文件。按“另存为”并选择“ASCI”文件格式。这对我的情况很有帮助,因为文件是 UTF8 格式,这就是原因。
Open PHP file in NOTEPAD. Press "Save as" and choose "ASCI" file format. This helped in my case, because file was in UTF8 format and this was the cause.