如何使用 mime 类型 octet-stream 从无扩展名的文件中提取文件扩展名?

问题描述 投票:0回答:1

我有大量文件,它们的原始文件名已被数据库中的 id 替换。例如,曾经的名称 word_document.doc 现在是 12345。经过一个过程,我失去了原来的名字。

我现在正在尝试提供这些文件以供下载。该人应该能够下载该文件并使用其原始应用程序查看它。这些文件均采用以下格式之一:

  • .txt(文本)
  • .doc(word文档)
  • .docx(word文档)
  • .wpd(完美单词)
  • .pdf (PDF)
  • .rtf(富文本)
  • .sxw(明星办公室)
  • .odt(开放式办公室)

我正在使用

$fhandle = finfo_open(FILEINFO_MIME);
$file_mime_type = finfo_file($fhandle, $filepath);

获取 mime 类型,然后将 mime 类型映射到扩展名。

我遇到的问题是某些文件的 mime 类型为 octet-stream。我在网上读过,这种类型似乎是二进制文件的杂项类型。我无法轻易说出扩展需要是什么。在某些情况下,当我将其设置为 .wpd 时它会起作用,而在某些情况下则不会。 .sxw.

也是如此
php mime-types fileinfo
1个回答
2
投票

Symfony2 只需 3 步即可完成

1) mime_content_type

$type = mime_content_type($path);

// remove charset (added as of PHP 5.3)
if (false !== $pos = strpos($type, ';')) {
    $type = substr($type, 0, $pos);
}

return $type;

2) 文件-b --mime

ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($path)), $return);
if ($return > 0) {
    ob_end_clean();

    return;
}

$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
    // it's not a type, but an error message
    return;
}

return $match[1];

3) 信息

if (!$finfo = new \finfo(FILEINFO_MIME_TYPE, $path)) {
    return;
}

return $finfo->file($path);

获得 mime-type 后,您可以从预定义的地图中获取扩展名,例如从 herehere

$map = array(
    'application/msword' => 'doc',
    'application/x-msword' => 'doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
    'application/pdf' => 'pdf',
    'application/x-pdf' => 'pdf',
    'application/rtf' => 'rtf',
    'text/rtf' => 'rtf',
    'application/vnd.sun.xml.writer' => 'sxw',
    'application/vnd.oasis.opendocument.text' => 'odt',
    'text/plain' => 'txt',
);
© www.soinside.com 2019 - 2024. All rights reserved.