通过Php提供.docx文件

5 php ms-word mime-types

尝试使用Php提供.docx文件时遇到问题.上传文件时,我检测文件mime类型,并使用基于mime类型的正确扩展名的文件上传文件; 例如下面:

application/msword - doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx
Run Code Online (Sandbox Code Playgroud)

当试图提供文件供下载时,我反过来检测扩展和基于mime类型的服务,例如

public static function fileMimeType($extention) {

        if(!is_null($extention)) {
            switch($extention) {
                case 'txt':
                    return 'text/plain';
                    break;
                case 'odt':
                    return 'application/vnd.oasis.opendocument.text';
                    break;
                case 'doc':
                    return 'application/msword';
                    break;
                case 'docx':
                    return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                    break;
                case 'jpg':
                    return 'image/jpeg';
                    break;
                case 'png':
                    return 'image/png';
                    break;
                case 'pdf':
                    return 'application/pdf';
                    break;
                default:
                    break;
            }
        }

}
Run Code Online (Sandbox Code Playgroud)

所有文件似乎都正确下载并打开正常,但在尝试打开docx文件时,Word(在多个文件上)会引发错误,指出文件已损坏.

任何想法都会很棒,谢谢.

编辑#1

try {

 $file = new Booking_Document((int)$get_data['bookingDocument']);
 header('Content-Type: ' . Booking_Document::fileMimeType($file->getDocumentType()));
 header('Content-Disposition: attachment; filename=' . $file);
 header('Expires: 0');
 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
 header('Pragma: public');
 echo readfile(Zend_Registry::get(static::$_uploadDir).$this->_id);
} catch (Exception $e) {
 View_Helpers_FlashMessages::addMessage(array('message' => $e->getMessage(), 'type' => 'error'));
}
exit;
Run Code Online (Sandbox Code Playgroud)

固定

在调用readfile()之前,我添加了ob_clean()和flush(),这似乎解决了问题.

小智 5

固定; 在调用readfile()之前,我添加了ob_clean()和flush(),这似乎解决了问题.