【问题标题】:PHP XLSX wrong MIME type detected检测到 PHP XLSX 错误的 MIME 类型
【发布时间】:2017-11-08 07:51:08
【问题描述】:

我正在尝试在上传时为 XLSX 文件检测正确的 MIME 类型,但到目前为止似乎没有什么对我有用。

$allowed_mimes = [
    'pdf'  => 'application/pdf',
    'png'  => 'image/png',
    'jpg'  => 'image/jpeg',
    'xls'  => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'doc'  => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'rtf'  => 'application/rtf',
    'odt'  => 'application/vnd.oasis.opendocument.text',
];
$finfo      = new finfo(FILEINFO_MIME_TYPE);
$is_allowed = array_search($finfo->file($attachment['tmp_name']), $allowed_mimes, true);
if (false === $is_allowed) {
    return [
        'error'   => true,
        'title'   => 'File format not supported',
        'message' => 'This file format is not supported yet. Format: ' . $finfo->file($attachment['tmp_name']),
    ];
}

我已经在.htaccess文件中使用了AddType

AddType application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xlsx

这似乎对我也不起作用。我在使用 Apache 的 VPS (Ubuntu) 上,我检查了 /etc/mime.types 文件并且 application/vnd.openxmlformats-officedocument.wordprocessingml.document 存在于那里。 /usr/share/mime/application/vnd.openxmlformats-officedocument.wordprocessingml.document.xml 文件也存在。我不确定是什么问题。

【问题讨论】:

    标签: php .htaccess ubuntu vps


    【解决方案1】:

    为什么不使用mime_content_type? 请注意,您必须提供正确的文件名和完整路径。 这段代码对我来说很好用:

    $allowed_mimes = [
        'pdf'  => 'application/pdf',
        'png'  => 'image/png',
        'jpg'  => 'image/jpeg',
        'xls'  => 'application/vnd.ms-excel',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'doc'  => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'rtf'  => 'application/rtf',
        'odt'  => 'application/vnd.oasis.opendocument.text',
    ];
    $is_allowed = array_search(mime_content_type($attachment['tmp_name']), $allowed_mimes, true);
    if (!$is_allowed) {
        return [
            'error'   => true,
            'title'   => 'File format not supported',
            'message' => 'This file format is not supported yet. Format: ' . mime_content_type($attachment['tmp_name']),
        ];
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 2015-10-05
      • 2018-04-08
      • 2010-10-13
      • 2015-09-17
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多