在使用php下载时,通过readfile()函数渲染的图像缺少扩展名


Extension missing for images rendered via readfile() function on downloading using php

从使用readfile函数渲染的图像下载的图像缺少扩展。

getphoto函数代码如下:
    <?php
    header('Content-Description: File Transfer');
    header('Access-Control-Allow-Origin:*');
    header('Cache-Control:public, max-age=864000');
    header('Content-Type:image/jpg');
    header('Expires: access plus 30 days');
    ob_clean();
    flush();
    readfile($filePath);
    ?>
    <img src="http://localhost/prjt/getphoto/ZmLj" />

您需要添加一个content-disposition标头:

   header('Content-Disposition: attachement; ' .
               ' filename="yourimage.suf"; size="'2311"');

这将告诉浏览器打开具有给定文件名的下载对话框。

接下来,在将图像的数据流式传输到客户机之后,您将不呈现html标记。而且,在把标题放在缓冲区后,你不应该用ob_clean擦除它们。完整代码:

<?php
    ob_clean();
    header('Content-Description: File Transfer');
    header('Access-Control-Allow-Origin:*');
    header('Cache-Control:public, max-age=864000');
    header('Content-Type:image/jpg');
    header('Expires: access plus 30 days');
    header('Content-Disposition: attachement; ' .
                   ' filename="yourimage.suf"; size="'2311"');
    readfile($filePath);
?>
// EOF !!