开发者

Serving .docx files through Php

开发者 https://www.devze.com 2023-02-02 19:32 出处:网络
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

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

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;
            }
        }

}

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.

Edit #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;

FIXED

Prior to calling readfile() I added ob_cle开发者_运维技巧an() and flush() which appears to have fixed the problem.


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


I had a similar problem some days ago. It was due to some characters being output just before the file was read. These chars were inserted at the beginning of the downloaded file, making it appear as corrupted when I tried to open it (PDF in this case).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号