通过Php提供.docx文件

时间:2011-01-05 09:49:55

标签: php ms-word mime-types

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

application/msword - doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document - docx

当试图提供文件供下载时,我会反过来检测扩展并根据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;
            }
        }

}

所有文件似乎都正确下载并且打开正常,但在尝试打开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;

固定

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

前几天我遇到了类似的问题。这是因为在读取文件之前输出了一些字符。这些字符被插入到下载文件的开头,当我尝试打开它时它显示为已损坏(在这种情况下为PDF)。