我從追加中獲取 Base64 字符串,然后用 PHP 對(duì)其進(jìn)行解碼并將其保存在數(shù)據(jù)庫中。該字符串可以是任何文件 .pdf、.img、.docx、.zip、.ppt、.docx 等。我的 base64 字符串不包含 mime 類型,例如“data:application/pdf;base64”部分。所以我需要獲取 base64 的 mime 類型。有什么辦法可以用PHP解決這個(gè)問題嗎?目前,我正在使用此代碼,它對(duì)于圖像和 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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
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
- 1 回答
- 0 關(guān)注
- 180 瀏覽
添加回答
舉報(bào)
0/150
提交
取消