Blob: type プロパティ

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

メモ: この機能はウェブワーカー内で利用可能です。

typeBlob インターフェイスの読み取り専用プロパティで、このファイルの MIME タイプを返します。

メモ: 現在の実装に基づくと、ブラウザーはファイルのバイトストリームを実際に読み込んで、そのメディア形式を決定するわけではありません。 ファイル拡張子に基づいて推測されます。PNG 画像ファイルの拡張子を .txt に変更すると、"text/plain" となり、"image/png" とはなりません。さらに、blob.type で信頼性が高いのは、画像、HTML 文書、音声、動画などの一般的なファイル形式のみです。 一般的ではないファイル拡張子は空文字列を返します。 クライアント構成(例えば、Windows レジストリー)は、一般的な形式であっても予期しない値になる可能性があります。 開発者は、このプロパティを唯一の検証手段として使用しないよう注意してください。

ファイルの MIME タイプを含む文字列、または型が特定できなかった場合は空文字列を指定します。

この例では、ユーザーにいくつかのファイルを選択してもらい、各ファイルが指定された画像ファイルタイプのセットのいずれかであるかどうかを確認します。

HTML

html
<input type="file" id="input" multiple />
<output id="output">画像ファイルを選択してください…</output>

JavaScript

js
// このアプリケーションは GIF, PNG, JPEG 画像のみを許可します
const allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];

const input = document.getElementById("input");
const output = document.getElementById("output");

input.addEventListener("change", (event) => {
  const files = event.target.files;

  if (files.length === 0) {
    output.innerText = "画像ファイルを選択してください…";
    return;
  }

  const allAllowed = Array.from(files).every((file) =>
    allowedFileTypes.includes(file.type),
  );
  output.innerText = allAllowed
    ? "すべてのファイルが合格です!"
    : "画像ファイルのみを選択してください。";
});

結果

仕様書

Specification
File API
# dfn-type

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
type

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Has more compatibility info.

関連情報