如何从PPT或docx的Base64字符串中获取MIME-TYPE



我从append中获取base64字符串,然后用PHP对其进行解码并将其保存在数据库中。

此字符串可以是任何文件.pdf、.img、.docx、.zip、.ppt、.docx等。

我的base64字符串不包括mime类型,例如"data:application/pdf;base64'部分。所以我需要得到base64的mime类型。

有什么方法可以用PHP解决这个问题吗?

目前,我正在使用这个代码,它可以很好地用于图像和pdf。

$file = base64_decode($formData['image'], true)
$mineType = $this->getMimeType($file);
public function getBytesFromHexString($hexdata)
{
for ($count = 0; $count < strlen($hexdata); $count += 2)
$bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
return implode($bytes);
}
public function getMimeType($imagedata)
{
$imagemimetypes = array(
"jpg" => "FFD8",
"png" => "89504E470D0A1A0A",
"gif" => "474946",
"bmp" => "424D",
"tiff" => "4949",
"pdf" => "25504446",
"docx"=> "504B0304",
"doc" => "D0CF11E0A1",
"xlsx"=> "504B030414000600",
"xls" => "D0CF11E0A1B11AE1"
);
foreach ($imagemimetypes as $mime => $hexbytes) {
$bytes = $this->getBytesFromHexString($hexbytes);
if (substr($imagedata, 0, strlen($bytes)) == $bytes){
return $mime;
}
}
return false;
}
function base64_mimetype(string $encoded, bool $strict = true): ?string {
if ($decoded = base64_decode($encoded, $strict)) {
$tmpFile = tmpFile();
$tmpFilename = stream_get_meta_data($tmpFile)['uri'];
file_put_contents($tmpFilename, $decoded);
return mime_content_type($tmpFilename) ?: null;
}
return null;
}

http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types