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; eg 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 eg
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_clean() 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.