通过 PHP 提供 .docx 文件 [英] Serving .docx files through Php

查看:39
本文介绍了通过 PHP 提供 .docx 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用 Php 提供 .docx 文件时遇到问题.上传文件时,我会检测文件 MIME 类型,并根据 MIME 类型使用具有正确扩展名的文件上传文件;例如下面:

I'm having issues when attempting to serve a .docx file using Php. When uploading the file I detect the file mime type and upload the file using the file with the correct extension based on the mime type; e.g. below:

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

当尝试提供文件以供下载时,我会根据 mime 类型检测扩展名和提供服务,例如

When attempting to serve the files for download, I do the reverse in detecting the extension and serving based on the mime type e.g.

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(在多个文件上)会引发错误,指出文件已损坏.

All files appear to download correctly and open fine but when attempting to open a docx file, Word (on multiple files) throws a error stating the file is corrupt.

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

Any ideas would be great, thanks.

编辑 #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(),这似乎解决了问题.

Prior to calling readfile() I added ob_clean() and flush() which appears to have fixed the problem.

推荐答案

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

Fixed; prior to calling readfile() I added ob_clean() and flush() which appears to have fixed the problem.

这篇关于通过 PHP 提供 .docx 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆