<input type=”file”> で選択できるファイルの拡張子を制限する方法
<input type="file"> でファイルを選択できますが、この時選択できるファイルの種類(拡張子)を制御するには、accept 属性で拡張子もしくはMIMEを設定します。
複数の拡張子を設定もできますし、ワイルドカードを使うこともできます。以下一例です。
<!-- 拡張子 .pdf -->
<input type="file" accept=".pdf">
<!-- MIME でテキストファイルを指定 -->
<input type="file" accept="text/plain">
<!-- MIMEでワイルドカード指定(画像ファイル) -->
<input type="file" accept="image/*">
<!-- 複数指定(画像もしくはPDF) -->
<input type="file" accept="image/*,.pdf">
<!-- 複数指定(.xlsxしくは.docx) -->
<input type="file" accept=".xlsx,.docx">
注意点
accept 属性で指定するのは厳密な制限ではなく、あくまでユーザーヒントです。開いたファイル選択ダイアログの初期状態では指定した種類のファイルしか選択できない状態ですが、ユーザー操作でファイル種類の変更が可能です。
適切なファイルが選択されているかどうかは、別途サーバー側で検証を行う必要があります。
MIME 一覧
以下代表的な拡張子に対応するMIMEタイプです。
| ファイル形式 | 拡張子 | MIMEタイプ |
|---|---|---|
| テキスト | .txt | text/plain |
| CSV | (CSV).csv | text/csv |
| HTML | .htm .html | text/html |
| XML | .xml | text/xml |
| JavaScript | .js | text/javascript |
| CSS | .css | text/css |
| Excel | .xls | application/vnd.ms-excel |
| Excel (OpenXML) | .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| Word | .doc | application/msword |
| Word(OpenXML) | .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| GIF | .gif | image/gif |
| JPEG | .jpg .jpeg | image/jpeg |
| PNG | .png | image/png |
| ビットマップ | .bmp | image/bmp |
| SVG | .svg | image/svg+xml |
| application/pdf | ||
| AAC音声 | .aac | audio/aac |
| MP4音声 | .mp4 .m4a | audio/mp4 |
| MPEG音声 | .mp1 .mp2 .mp3 .mpg .mpeg | audio/mpeg |
| OGG音声 | .oga .ogg | audio/ogg |
| WAV音声 | .wav | audio/wav |
| WebM音声 | .webm | audio/webm |
| MP4ビデオ | .mp4 .m4v | video/mp4 |
| OGGビデオ | .ogv | video/ogg |
| WebMビデオ | .webm | video/webm |
| ZIP | .zip | application/zip |
| 7-zip | .zip | application/x-7z-compressed |
text/csv は効かない
text/csv の指定で “.csv” のファイルのみと制限をつけられるはずですが、なぜかうまく効きません。IE11, Chrome, Firefox で確認しましたがいずれも動作しませんでした。
拡張子での指定は効くので、.csv を指定すればOKです。
コメントを書く