【发布时间】:2011-06-03 21:54:26
【问题描述】:
我在尝试使用 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(),这似乎已经解决了问题。
【问题讨论】:
-
case ('jpg' || 'jpeg'):不行,需要写case 'jpg': case 'jpeg':。 -
类似问题,可能有帮助:stackoverflow.com/questions/179315/…
-
您在客户端收到的结果是什么?保存到磁盘时它是有效文件吗?
-
是否发送了正确的 MIME 标头?使用 Firebug/其他浏览器控制台检查。
-
您可以尝试使用旧的
'application/octet-stream'。不如使用正确的 mime 类型好,但值得尝试看看它是否有效。
标签: php ms-word mime-types