我正在尝试从无框架PHP服务器上的FTP读取/下载文件(是的(。我所实现的对PDF文件工作良好:它打开一个选项卡并毫无问题地显示它们。但我对.doc
、.docx
或even .odt
文件有问题。使用Libre Office,我得到了一个包含不可读内容的文件,如:��R#���X�A9#]��ja��b(�>e��-�8a�1�1,!~k��#���Lލ��j��dl����
。但是,我确信FTP服务器上存储的文件是有效的。(如果我用FTP客户端下载,我会得到一个可读的文件(。
以下是我获取文件的方式:
header("Content-type: $mimeType");
header('Content-Disposition: inline; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
if (!ftp_get($connexion, "php://output", $filename, FTP_BINARY)) {
echo "Couldn't read $filename";
}
ftp_close($connexion);
一些信息:
它在本地存储的文件上工作,使用
ob_end_clean();
readfile($file);
当我使用ftp_get()
时,问题确实发生了。CCD_ 6是根据文件扩展名动态设置的。我尝试使用FTP_ASCII
模式,我尝试使用其他php://flux,我尝试设置Content-Transfer-Encoding: 8bit
而不是binary
。。。还是一样。
多亏了04FS,它才能工作。有趣的是,在尝试了04FS的解决方案后,我最初的方法最终奏效了,只需在~~之前清除ouptut缓冲区。
04FS的建议解决方案:
$filename = "ftp://".FTP_USER.":".FTP_PASS."@".FTP_HOST."/$filename";
ob_clean();
$content = file_get_contents($filename);
$handle = fopen('php://memory', 'w');
fwrite($handle, $content);
rewind($handle);
header("Content-type: $mimeType");
header('Content-Disposition: attachment;filename="' . $filename . '";');
fpassthru($handle);
fclose($handle);
然后我用ob_clean()
和。。。它有效。
ob_clean();
header("Content-type: $mimeType");
header('Content-Disposition: inline; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
if (!ftp_get($connexion, "php://output", $filename, FTP_BINARY)) {
echo "Couldn't read $filename";
}
ftp_close($connexion);
.pdf
文件不需要它,但它适用于.doc
、.docx
等…