没有不值得去解决的问题,也没有不值得去学习的技术!

mime_content_type — Detect a File’s MIME Type: Replace the Implementation With league/mime-type-detection

Implemented based on Mime-type Detection league/mime-type-detection league/mime-type-detection

1. Reference: The same CSS file (with equal Etags) causes differences in the web interface due to differences in the response Content-Type. I found that the response Content-Type is implemented based on mime_content_type — Detects the MIME type of a file, which is ultimately implemented based on Mime-type Detection league/mime-type-detection league/mime-type-detection. It detects by content, falling back to detection by extension. See Figure 1.

Implemented based on Mime-type Detection league/mime-type-detection league/mime-type-detection
Figure 1
PHP

use League\MimeTypeDetection\ExtensionMimeTypeDetector;

$this->detector = new ExtensionMimeTypeDetector();

Log::info(
	$return['asset_key'],
	[
		$return['asset_key'],
		$this->detector->detectMimeTypeFromPath($fullPath),
	]
);

Plaintext

[2023-05-18 14:00:04] local.INFO: apps/internal/code-display/blocks/code-display.blade.php [
    "apps/internal/code-display/blocks/code-display.blade.php",
    "application/x-httpd-php"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/.env.local [
    "apps/internal/comment/.env.local",
    null
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/app.json [
    "apps/internal/comment/app.json",
    "application/json"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/assets/app.6e10b7.css [
    "apps/internal/comment/assets/app.6e10b7.css",
    "text/css"
] 
[2023-05-18 14:00:04] local.INFO: apps/internal/comment/assets/app.f8ed5d.js [
    "apps/internal/comment/assets/app.f8ed5d.js",
    "application/javascript"
] 
[2023-05-18 14:00:05] local.INFO: apps/internal/custom-button/assets/images/ali-express-large.8fdc24.png [
    "apps/internal/custom-button/assets/images/ali-express-large.8fdc24.png",
    "image/png"
] 
[2023-05-18 14:00:07] local.INFO: apps/internal/sharing-incentives/assets/images/sparkles.a0d182.jpg [
    "apps/internal/sharing-incentives/assets/images/sparkles.a0d182.jpg",
    "image/jpeg"
] 

2. I checked the generated Content-Type, and it meets expectations. When the corresponding extension does not exist, it returns null. In this case, fallback handling is needed.

PHP

Log::info(
	$return['asset_key'],
	[
		$return['asset_key'],
		$this->detector->detectMimeTypeFromPath($fullPath) ?? mime_content_type($fullPath),
	]
);

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系