MIME タイプを調べる方法
ファイル拡張子に対応する MIME(コンテンツ)タイプを調べます。逆方向の検索にも対応します。
问题
ファイルに正しい Content-Type ヘッダーを設定する必要があるか、拡張子からファイルの種類を判定する必要があります。
前提条件
- HTTP ヘッダーの理解
- ファイル形式に関する知識
ステップ
-
1. Look up by file extension
Map the file extension to its MIME type: .json → application/json, .html → text/html, .png → image/png, .pdf → application/pdf. Use a comprehensive MIME type database for accurate mapping, as some extensions have multiple registered types.
入力.json输出application/json -
2. Handle ambiguous extensions
Some extensions map to multiple MIME types depending on context: .xml can be text/xml or application/xml, .js can be text/javascript or application/javascript. Use the most widely compatible type. For web serving, follow the IANA registry.
入力.xml输出application/xml (preferred) -
3. Set the Content-Type correctly
When serving files, set the Content-Type header to the correct MIME type. Browsers use this to determine how to handle the response. An incorrect type can cause a file to download instead of display, or render incorrectly. Add charset for text types: text/html; charset=utf-8.
入力serving a JSON file输出Content-Type: application/json; charset=utf-8
期待される結果
ファイル拡張子に対応する正しい MIME タイプ、または MIME タイプに対応する正しい拡張子。
よくあるエラー
- Wrong Content-Type causes file to download
- Set the correct MIME type. For example, text/html for HTML, application/json for JSON. A wrong type like application/octet-stream causes download.
- Missing charset for text types
- Add charset=utf-8 to text MIME types (text/html, text/plain, application/json). Without it, the browser may guess the encoding incorrectly.
トラブルシューティング指引
- If a file renders as plain text, the Content-Type is likely text/plain instead of the correct type.
- For custom file types, use application/octet-stream as a fallback.
セキュリティ上の制限
- MIME type sniffing can be a security risk. Set X-Content-Type-Options: nosniff to prevent browsers from guessing the type.