首页 > 解决方案 > 下载php文件时随机添加字节

问题描述

我正在尝试从使用 PHP 的服务器下载二进制文件。下载时,它会以某种方式在文件的前面随机添加一个字节:

结果下载(十六进制编辑器图像):

十六进制编辑器图像

预期结果下载(十六进制编辑器图像):

我尝试过的事情:
1.标题接近尝试1

$filename = 'spss-export.sav';
header("Content-Disposition: attachment; filename=survey_2_SPSS_syntax_file.sav");
header("Content-type: application/download; charset=UTF-8");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: public");
readfile($filename); // do the double-download-dance (dirty but worky)
exit;

2.标题方法尝试2

$filename = 'spss-export.sav';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($filename) . "\"");
readfile($filename); // do the double-download-dance (dirty but worky)
exit;

3. Laravel 响应下载

$filename = 'spss-export.sav';
return response()->download($filename);

标头方法生成的文件在开头只有随机字节,但 laravel 方法在文件末尾生成随机字节和一个丢失的字节。任何人都知道可能是什么问题?

标签: phplaravelfilebinarybyte

解决方案


自己找到了答案:您必须在文件输出之前添加ob_end_clean() 。laravel 框架以某种方式为文件添加了额外的空间。

如果这不起作用,请参考:
https ://drupal.stackexchange.com/questions/163628/extra-space-at-beginning-of-downloaded-image/163644#163644


推荐阅读