为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 PPT 或 docx 的 Base 64 字符串获取 MIME-TYPE?

如何从 PPT 或 docx 的 Base 64 字符串获取 MIME-TYPE?

PHP
紫衣仙女 2023-10-22 21:47:20
我从追加中获取 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;}
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

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


查看完整回答
反对 回复 2023-10-22
  • 1 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信