Blob: type 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

注意:此功能在 Web Workers 中可用。

Blob 接口的 type 只读属性返回文件的 MIME 类型

注意:根据当前的实现,浏览器并不会真正读取文件的字节流来确定其媒体类型。它会根据文件扩展名来假设;一个被重命名为 .txt 的 PNG 图像文件将返回 "text/plain" 而不是 "image/png"。此外,blob.type 通常只对常见的文档类型(如图像、HTML 文档、音频和视频)可靠。不常见的文件扩展名将返回空字符串。客户端配置(例如,Windows 注册表)即使对于常见类型也可能导致意外值。建议开发者不要将此属性作为唯一的验证方案。

包含文件 MIME 类型的字符串,如果无法确定类型,则为空字符串。

示例

此示例要求用户选择多个文件,然后检查每个文件以确保它是给定的一组图像文件类型之一。

HTML

html
<input type="file" id="input" multiple />
<output id="output">Choose image files…</output>

JavaScript

js
// Our application only allows GIF, PNG, and JPEG images
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 = "Choose image files…";
    return;
  }

  const allAllowed = Array.from(files).every((file) =>
    allowedFileTypes.includes(file.type),
  );
  output.innerText = allAllowed
    ? "All files clear!"
    : "Please choose image files only.";
});

结果

规范

规范
File API
# dfn-type

浏览器兼容性

另见